死锁(Deadlock)描述了一种情况,其中两个或多个线程永远被阻塞,互相等待。这有一个例子。
Alphonse和Gaston是朋友,也是礼貌的忠实信徒。严格的礼貌规则是当您向朋友鞠躬时,您必须保持鞠躬,直到您的朋友有机会结束鞠躬为止。不幸的是,该规则不能解决两个朋友可能同时鞠躬的可能性。示例应用程序Deadlock
对这种可能性进行建模:
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();
}
}
Deadlock
运行时,两个线程极有可能在尝试调用bowBack
时阻塞。 任何一个块都不会结束,因为每个线程都在等待另一个退出bow
。