我有一个来自oracle.com的示例,但我不明白。.请解释一下。一个线程运行弓,然后它运行回弓,但是为什么什么都没打印出来?
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();
}
}
最佳答案
这是导致僵局的情况:
线程1调用alphonse.bow()
并因此获得alphonse的锁
线程2调用gaston.bow()
并因此获得加斯顿的锁
线程1想调用gaston.bowBack()
,但是阻塞直到加斯顿锁被释放
线程2想要调用alphonse.bowBack()
,但是直到alphonse的锁被释放为止才阻塞
因此,两个线程都无限地等待。
关于java - 为什么Java在这里死锁?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18623554/