谁能告诉我为什么此代码遭受死锁?

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();
        }
    } }

最佳答案

Thread1启动并获取lock1lock2Thread1释放lock1(带有lock1.wait())。
Thread2启动并获取lock1,然后永远等待lock2Thread1正在等待通知,但永远不会收到通知。

DEADLOCK!

09-03 21:19