マルチスレッドのシナリオでDeadlockを記述した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)。 –