我在Oracle的Java教程中遇到了这个example,它描述了多线程场景中的死锁。使用System.out.format和System.out.println进行多线程处理
因此,在这个例子中我提出以下在第17行的变化和线18
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) {
//My Changes
//System.out.format("%s: %s" + " has bowed to me!%n", this.name, bower.getName()); //Line 17
System.out.println(this.name + ": " + bower.getName() + " has bowed to me!"); //Line 18
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() {
@Override
public void run() {
alphonse.bow(gaston);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
gaston.bow(alphonse);
}
}).start();
}
}
在这样做这些改变,而不会引起死锁成功地终止该程序和打印输出如下
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!
因此,我问题是 - 为什么它的行为如此? println声明如何防止死锁?
我看不出它会如何。 'System.out.format'在锁定方面与'System.out.println'不同。 –
它没有区别 - 只是死锁取决于线程交错,这在运行之间会有所不同。如果使用System.format多次运行它,您可能会不时观察到正确的输出。使用println,您还会看到程序死锁的运行。 – assylias
确实:第一个变体[可以在ideone上正常运行](http://ideone.com/bV6nd8)。 –