java之死锁

1.死锁是什么?

  死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。

      

2.死锁形成条件

    Ⅰ.互斥条件:进程要求对所分配的资源进行排它性控制,即在一段时间内某资源仅为一进程所占用。(某资源 一次只能一个

    Ⅱ.请求和保持条件:当进程因请求资源而阻塞时,对已获得的资源保持不放。(拿到就不释放

    Ⅲ.不剥夺条件:进程已获得的资源在未使用完之前,不能剥夺,只能在使用完时由自己释放。(不能抢占别人的

    Ⅳ.环路等待条件:在发生死锁时,必然存在一个进程--资源的环形链。(循环等待

3.死锁代码实现

/**
 * Created by sk on 2021/1/14
 */
public class Host {

    public static void main(String[] args) {

        Object a = new Object();
        Object b = new Object();

        new Thread(()->{
            //锁住a
            synchronized (a) {
                System.out.println(Thread.currentThread().getName()+"线程a");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //尝试锁b
                System.out.println(Thread.currentThread().getName()+"我想拿b");
                synchronized (b) {
                    System.out.println("线程b");
                }
            }
        }).start();

        new Thread(()->{
            //锁住b
            synchronized (b) {
                System.out.println(Thread.currentThread().getName()+"线程b");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //尝试锁a
                System.out.println(Thread.currentThread().getName()+"我想拿a");
                synchronized (a) {
                    System.out.println("线程a");
                }
            }
        }).start();

    }

}

4.执行结果

查看死锁位置:

jps
jstack xxxx

原文地址:https://www.cnblogs.com/songxiaoke/p/14275949.html