Could someone please explain why the following code results in deadlock.
My understanding is that when alphonse(thread) run then it acquires lock on friend obj because it invokes bow() method but how come gaston(another thread) is able to acquires the lock on the same friend obj while the alphonse haven't finished/released the lock on friend obj.
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) {
System.out.println("invoked by " + name);
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
System.out.printf("finished by " + name);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
System.out.println("exiting bowBack()");
}
}
public static void main(String[] args) throws InterruptedException {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}