segmentfault-lessons icon indicating copy to clipboard operation
segmentfault-lessons copied to clipboard

「一入 Java 深似海 」第3期2节死锁有问题

Open purgeyao opened this issue 5 years ago • 2 comments

不加线程等待会出现一个线程执行完成,第二个线程才执行(偶尔出现) 在每个线程第一个对象获取锁之后加线程等待可以解决这个问题 public class ThreadDeadLock {

public static void main(String[] args) {

    Object o1 = new Object();

    Object o2 = new Object();

    Thread thread1 = new Thread(() -> {

        synchronized (o1){
            System.out.println(Thread.currentThread() + " get o1");
            // 线程等待
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o2){
                System.out.println(Thread.currentThread() + " get o2");
            }
        }
    });

    Thread thread2 = new Thread(() -> {

        synchronized (o2){
            System.out.println(Thread.currentThread() + " get o2");
            // 线程等待
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o1){
                System.out.println(Thread.currentThread() + " get o1");
            }
        }
    });

    thread1.start();
    thread2.start();
}

}

purgeyao avatar Mar 18 '19 13:03 purgeyao

欢迎提交 PR~

mercyblitz avatar Mar 18 '19 14:03 mercyblitz

我的理解是:由于o1对象引用了o2对象,o2对象又引用了o1对象,并且o1与o2都加了同步锁,相互不释放,因此进入了死锁。

myejb22 avatar Mar 19 '19 01:03 myejb22