The example illustrates how deadlock happens. There is one thing I don't understand, which is that when the first thead that calls method bow of instance alphone is about to execute gaston.bowbBack (this), does the thread will release lock and acquire the lock of the instance gaston if, suppose, it is not owned by the second thread? or will it hold two locks at the same time utill all the code of the method is executed completely? And another question, is there any way to check whether a thread is holding a lock?
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.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
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() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}