我正在查看 oracle 文档中的死锁.. 我找到了这段代码
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();
}
}
我无法理解,在什么情况下会发生死锁?
我运行这段代码,它工作正常。那么一定有什么特殊的事件,什么时候会发生死锁呢?
假设先在对象上调用 bow ,当在 bower 对象上调用时,它是否会离开对对象alphonse
的锁定?因为如果它保留它的锁,另一个对象上的函数在离开它的锁之前不会获得锁,它永远不会出现死锁情况。alphonse
bower.bowBack(this)
bow
alphonse