我正在学习Java中的死锁,并且有来自Sun官方教程的示例代码:
阿方斯和加斯顿是朋友,也很有礼貌的信徒.严格的礼貌规则是,当你向朋友鞠躬时,你必须保持鞠躬,直到你的朋友有机会归还弓箭.不幸的是,这条规则没有考虑到两个朋友可能同时互相鞠躬的可能性.
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"); …Run Code Online (Sandbox Code Playgroud)