【发布时间】:2010-02-16 05:48:25
【问题描述】:
下面是直接来自描述死锁的 Sun 教程的代码。但是,考虑到两种方法都是同步的,我不明白在这种情况下如何发生死锁。两个线程如何同时在同一个同步方法中?
死锁描述了两个或多个线程被永远阻塞,相互等待的情况。这是一个例子。
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 时极有可能会阻塞。这两个块都不会结束,因为每个线程都在等待另一个退出弓。
【问题讨论】:
标签: java