我发现了这个可能导致Oracle's official Java site.
死锁的代码示例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();
}
}
有人可以解释为什么它可能导致死锁吗?
当第一个朋友(" Alphonse")为run
时,它会执行bow
并在另一个朋友上调用bowBack
。在发生这种情况的某个地方,第二个朋友(" Gaston")运行,它执行自己的bow
版本并在Alphonse上调用bowBack
。那么哪里有僵局?他们都在调用自己的方法版本。