Mutithreading mit System.out.format und System.out.println
Ich bin auf dieses @ gestoßBeispie im Java Tutorial von Oracle, das Deadlock in Multithreading-Szenarien beschreibt.
So habe ich in diesem Beispiel folgende Änderungen in Zeile 17 und Zeile 18 vorgenommen.
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();
}
}
enn Sie diese Änderungen vornehmen, wird das Programm erfolgreich ohne Deadlock beendet und nach der Ausgabe gedruck
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!
Also meine Frage ist- warum hat es sich so verhalten? Wie hat die println-Anweisung den Deadlock verhindert?