我发现在经典的Java 死锁教程中包含对 System.out.format 的调用将防止死锁发生,我不知道为什么。
下面的代码和教程的一样,只是增加main
了System.out.format("Hi, I'm %s...no deadlock for you!\n\n", alphonse.getName());
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) throws InterruptedException {
final Friend alphonse = new Friend("Alphonse");
final Friend gaston = new Friend("Gaston");
System.out.format("Hi, I'm %s...no deadlock for you!\n\n", alphonse.getName());
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
这是输出:
Hi, I'm Alphonse...no deadlock for you!
Alphonse: Gaston has bowed to me!
Gaston: Alphonse has bowed back to me!
Gaston: Alphonse has bowed to me!
Alphonse: Gaston has bowed back to me!
删除有问题的行会导致通常的死锁:
Alphonse: Gaston has bowed to me!
Gaston: Alphonse has bowed to me!
... deadlock ...
对 System.out.format 的调用是否以某种方式改变了线程获取对象内部锁的方式?
更新:
只需更改我在代码中启动线程的位置,我就能让系统再次死锁:
public static void main(String[] args) throws InterruptedException {
final Friend alphonse = new Friend("Alphonse");
final Friend gaston = new Friend("Gaston");
System.out.format("Hi, I'm %s...no deadlock for you!\n\n", alphonse.getName());
Thread t1 = new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
});
Thread t2 = new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
});
t1.start();
t2.start();
}
这就引出了一个问题,即我们如何才能更深入地了解线程调度程序的行为,但我将把它留到另一天。