为什么下面的代码有死锁?

时间:2013-10-02 14:08:44

标签: java multithreading deadlock

任何人都可以告诉我为什么这段代码会遇到死锁?

public class BrokenOrderingReentredLock implements Runnable {

    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public static void main(String[] args) throws InterruptedException {
        BrokenOrderingReentredLock runnable = new BrokenOrderingReentredLock();
        Thread thread1 = new Thread(runnable, "thread1");
        Thread thread2 = new Thread(runnable, "thread2");
        thread1.start();
        Thread.sleep(500);
        thread2.start();
    }

    @Override
    public void run() {
        try {
            String threadName = Thread.currentThread().getName();
            synchronized (lock1) {
                System.out.println(threadName + " has lock1");
                synchronized (lock2) {
                    System.out.println(threadName + " has lock2");
                        System.out.println(threadName + " reenters lock1");
                        lock1.wait();
                        lock2.wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } }

2 个答案:

答案 0 :(得分:7)

Thread1启动并获取lock1lock2Thread1发布lock1lock1.wait())。

Thread2启动并获取lock1,然后永远等待lock2Thread1等待通知,但永远不会。

DEADLOCK!

答案 1 :(得分:0)

发生的事情是thread1获取lock1上的锁定然后锁定lock2。然后,Thread1调用lock1.wait,它释放lock1上的锁,并让thread1在那里等待,直到有人调用notify(从未发生过)。

Thread2出现并锁定lock1。然后阻止它锁定lock2,因为thread1仍然具有锁定。

如果你在lock1.wait和lock2.wait之间放一条消息,你会发现两个线程都没有那么远,所以锁定在lock2上永远不会被释放。