原理:

T1对A加锁成功后,挂到lock这把锁上面去等待,被唤醒后再去对B加锁。
T2对B加锁后,挂到lock这把锁上面去等待,然后再去对A加锁。
然后用mian线程把T1、T2同时唤醒。

public class DeadLockDemo {

    public static void main(String[] args) {
        Object A = new Object();
        Object B = new Object();
        //用lock这把锁来保证T1和T2间的通信
        Object lock = new Object();
        //线程对象本身这把锁是否要获得才能继续执行下去?
        CountDownLatch countDownLatch=new CountDownLatch(2);

        new Thread(() -> {
            synchronized (A) {
                System.out.println("T1线程已经拿到A锁");
                synchronized (lock) {

                    try {
                        countDownLatch.countDown();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                synchronized (B) {
                    System.out.println("T1线程已经拿到B锁");
                }
            }
            System.out.println("T1线程执行完毕");
        }, "T1").start();

        new Thread(() -> {
            synchronized (B) {
                System.out.println("T2线程已经拿到B锁");
                synchronized (lock) {
                    try {
                        countDownLatch.countDown();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                synchronized (A) {
                    System.out.println("T2线程已经拿到A锁");
                }
            }
            System.out.println("T2线程执行完毕");
        }, "T2").start();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (lock) {
            lock.notifyAll();
        }
    }
}

Winson
6 声望1 粉丝

把原本的个人笔记迁移到这里