死锁 - 在这个例子中是如何发生的?
2022-09-02 00:49:38
任何人都可以解释:
- 为什么我们会陷入僵局?
- 加斯顿如何在阿方斯退出该功能之前进入功能弓?(它应该从函数返回才能退出函数 - or)?
bowBack()
bow()
这是我得到的输出 - 然后程序卡住了!
阿方斯: 加斯顿向我鞠躬了!
加斯顿: 阿方斯向我鞠躬了!
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse = new Friend("Alphonse");
final Friend gaston = new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}