gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:06:46 25 4
gpt4 key购买 nike

谁能告诉我为什么这段代码会死锁?

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 正在等待通知,但永远不会。

僵局!

关于java - 为什么下面的代码有死锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19138939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com