1 死锁定义

死锁是指,两个或两个以上的线程在执行过程中,由于竞争资源而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。简化一点说就是:一组相互竞争资源的线程因为互相等待,导致“永久”阻塞的现象

例如下面案例:

public class DeadLockTest {
    private static String A = "A";
    private static String B = "B";

    public static void main(String[] args) {
        new DeadLockTest().deadLock();
    }

    private void deadLock() {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (A) {
                    System.out.println("t1成功获取A锁");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (B) {
                        System.out.println("t1成功获取B锁");
                    }
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (B) {
                    System.out.println("t2成功获取B锁");
                    synchronized (A) {
                        System.out.println("t2成功获取A锁");
                    }
                }
            }
        });
        t1.start();
        t2.start();
    }
}

t1锁住了A,然后尝试对B进行加锁,同时t2已经锁住了B,接着尝试对A进行加锁,这时死锁就发生了。t1永远得不到B,t2也永远得不到A,它们将永远阻塞下去。

Thread 1  locks A, waits for B
Thread 2  locks B, waits for A

可以使用 jps 定位进程 id,再用 jstack 定位死锁。

D:\workplace\GiteeProjects\java-learn\concurrent-learn\src\main\java\com\kai\demo\basic>jps
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=gb2312
21812 Jps
15848 RemoteMavenServer36
25132 KotlinCompileDaemon
25580
27516 DeadLockTest
29052 Launcher

D:\workplace\GiteeProjects\java-learn\concurrent-learn\src\main\java\com\kai\demo\basic>jstack 27516
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=gb2312
2020-10-31 17:27:38
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.261-b12 mixed mode):

"DestroyJavaVM" #14 prio=5 os_prio=0 tid=0x0000016945db5000 nid=0xfd0 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Thread-1" #13 prio=5 os_prio=0 tid=0x0000016962b9b800 nid=0x1814 waiting for monitor entry [0x00000005fc8ff000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at com.kai.demo.basic.DeadLockTest$2.run(DeadLockTest.java:47)
        - waiting to lock <0x000000076bf40af8> (a java.lang.String)
        - locked <0x000000076bf40b28> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

"Thread-0" #12 prio=5 os_prio=0 tid=0x0000016962b03000 nid=0x6490 waiting for monitor entry [0x00000005fc7ff000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at com.kai.demo.basic.DeadLockTest$1.run(DeadLockTest.java:35)
        - waiting to lock <0x000000076bf40b28> (a java.lang.String)
        - locked <0x000000076bf40af8> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

--- omit ---

Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x0000016960a81c38 (object 0x000000076bf40af8, a java.lang.String),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x0000016960a84578 (object 0x000000076bf40b28, a java.lang.String),
  which is held by "Thread-1"

Java stack information for the threads listed above:
===================================================
"Thread-1":
        at com.kai.demo.basic.DeadLockTest$2.run(DeadLockTest.java:47)
        - waiting to lock <0x000000076bf40af8> (a java.lang.String)
        - locked <0x000000076bf40b28> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)
"Thread-0":
        at com.kai.demo.basic.DeadLockTest$1.run(DeadLockTest.java:35)
        - waiting to lock <0x000000076bf40b28> (a java.lang.String)
        - locked <0x000000076bf40af8> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.

2 避免死锁

产生死锁的四个必要条件:

(1) 互斥:一个资源每次只能被一个线程使用。
(2) 请求与保持:一个线程因请求资源而阻塞时,不释放已获得的资源。
(3) 不剥夺:进程已获得的资源,在末使用完之前,不能强行剥夺。
(4) 循环等待:若干线程之间形成一种头尾相接的循环等待资源关系。例如上述案例中,线程 t1 等待线程t2占有的资源,线程t2等待线程t1占有的资源。

只有这四个条件都发生时才会出现死锁,那么反过来,也就是说只要我们破坏其中一个,就可以成功预防死锁的发生

编写程序时避免死锁的常见方法:

(1)避免一个线程同时获取多个锁。

(2)避免一个线程在锁内同时占用多个资源,尽量保证每个锁只占用一个资源。

(3)尝试使用定时锁,使用lock.tryLock(timeout)来替代使用内部锁机制。

(4) 对于数据库锁,加锁和解锁必须在一个数据库连接里,否则会出现解锁失败的情况。

3 哲学家就餐问题

哲学家就餐问题是1965年由Dijkstra提出的一种线程同步的问题。

问题描述:一圆桌前坐着5位哲学家,每两个人中间有一只筷子,桌子中央有面条。哲学家思考问题,当饿了的时候拿起左右两只筷子吃饭,必须拿到两只筷子才能吃饭。上述问题会产生死锁的情况,当5个哲学家都拿起自己右手边的筷子,准备拿左手边的筷子时产生死锁现象。

用代码描述就是:

public class DeadLockTest2 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        int sum = 5;
        Chopstick[] chopsticks = new Chopstick[sum];
        for (int i = 0; i < sum; i++) {
            chopsticks[i] = new Chopstick();
        }
        for (int i = 0; i < sum; i++) {
            executorService.execute(new Philosopher(chopsticks[i], chopsticks[(i + 1) % sum]));
        }
    }
}

class Philosopher implements Runnable {
    private Chopstick left;
    private Chopstick right;

    public Philosopher(Chopstick left, Chopstick right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(1000);// 思考一段时间
                synchronized (left) {// 获取左手边筷子
                    synchronized (right) {// 获取右手边筷子
                        Thread.sleep(1000);// 进餐
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

// 筷子
class Chopstick {
    public Chopstick() {
    }
}

3.1 破坏循环等待条件

不再按左手边右手边顺序拿起筷子。选择一个固定的全局顺序获取,此处给筷子添加id,根据id从小到大获取,(不用关心编号的具体规则,只要保证编号是全局唯一并且有序的),不会出现死锁情况。

public class DeadLockTest2 extends Thread {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        int sum = 5;
        Chopstick[] chopsticks = new Chopstick[sum];
        for (int i = 0; i < sum; i++) {
            chopsticks[i] = new Chopstick(i);
        }
        for (int i = 0; i < sum; i++) {
            exec.execute(new Philosopher(chopsticks[i], chopsticks[(i + 1) % sum]));
        }
    }
}

class Chopstick {
    //状态
    private int id;

    public Chopstick(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

// 哲学家
class Philosopher implements Runnable {

    private Chopstick left;
    private Chopstick right;

    public Philosopher(Chopstick left, Chopstick right) {
        if (left.getId() < right.getId()) {
            this.left = left;
            this.right = right;
        } else {
            this.left = right;
            this.right = left;
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName()+"思考一段时间");
                synchronized (left) {
                    System.out.println(Thread.currentThread().getName()+"获取到第一只筷子");
                    synchronized (right) {
                        System.out.println(Thread.currentThread().getName()+"获取到第二只筷子");
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName()+"进餐一段时间");
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

执行结果:

pool-1-thread-4思考一段时间
pool-1-thread-4获取到第一只筷子
pool-1-thread-4获取到第二只筷子
pool-1-thread-5思考一段时间
pool-1-thread-5获取到第一只筷子
pool-1-thread-1思考一段时间
... ...

3.2 破坏请求与保持条件

使用可重入锁ReentrantLock来避免死锁。使用内置锁的线程获取不到锁时会被阻塞,而ReentrantLock是可重入的,也可以指定一个超时时限(调用tryLock(long timeout, TimeUnit unit)方法),在等待超过该时间后tryLock就会返回一个失败信息,释放所持有的资源。

class Philosopher extends Thread{
    private ReentrantLock left,right;

    public Philosopher(ReentrantLock left, ReentrantLock right) {
        super();
        this.left = left;
        this.right = right;
    }
    public void run(){
        try {
            while(true){
                Thread.sleep(1000);//思考一段时间
                left.lock();
                try{
                    if(right.tryLock(1000,TimeUnit.MILLISECONDS)){
                        try{
                            Thread.sleep(1000);//进餐一段时间
                        }finally {
                            right.unlock();
                        }
                    }else{
                        //没有获取到右手的筷子,放弃并继续思考
                    }
                }finally {
                    left.unlock();
                }
            }
        } catch (InterruptedException e) {
        }~~~~
    }
}

参考资料

【Java并发基础】死锁

哲学家就餐问题与死锁总结


思思问问
27 声望5 粉丝

Stay Hungry, Stay Foolish!