【发布时间】:2020-04-17 00:00:34
【问题描述】:
我正在查看几个死锁示例,并在使用 Oracle 示例时发现了一些有趣的事情:https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html。
如果您替换此行: System.out.format("%s: %s" + " 已经向我鞠躬了!%n", this.name, bower.getName());
与: System.out.println(this.name + "已经向我鞠躬了!" + bower.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) {
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();
}
}
【问题讨论】:
-
请在问题中包含相关代码。时间链接坏了。