This code comes from Oracle tutorial about concurrency. I don't understand why synchronizing methods leads to deadlock
. When methods are not synchronized
everything works fine, but when I add synchronized
keyword, program stops and method bowBack()
is never invoked. Could someone explain in affordable manner why it happens? Below is mentioned code snippet:
public class Deadlock {
static class Friend {
private final String name;
Friend(String name) {
this.name = name;
}
String getName() {
return this.name;
}
synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
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(() -> alphonse.bow(gaston)).start();
new Thread(() -> gaston.bow(alphonse)).start();
}
}