I got the idea about why deadlock happens Deadlock example
and read the related questionsenter link description here
But, I modified the sample code by adding Thread.sleep(1000)
between two start() call and this program was not blocked by deadlock.
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) throws Exception {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
Thread.sleep(1000);
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
I'd like to know why this happens.
Is there any chance to exit normally without deadlock?