我在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)。 –