我发现在经典Java Deadlock Tutorial中包含对System.out.format的调用将防止发生死锁,并且我找不到原因。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的调用。格式以某种方式改变线程获取对象的内部锁的方式?
更新:
我能得到系统只是通过改变再次陷入僵局,我的代码启动线程:
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();
}
这就引出了我们如何能够得到更深入的了解这个问题进入线程调度程序的行为方式,但我会在不同的一天保存它。
当您添加该行时,第一个线程在主线程启动第二个线程之前完成。 –
但是,这只是巧合在一个特定的处理器和调度程序。仍然不能保证不会发生死锁。 – Wyzard