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());
    }
  }

  static class Bower extends Thread {
    private Friend bower, bowed;
    public Bower(Friend bower, Friend bowed) {
      this.bower = bower;
      this.bowed = bowed;
    }
    public void run() {
      bower.bow(bowed);
    }
  }

  public static void main(String[] args) {
    final Friend alphonse = new Friend("Alphonse");
    final Friend gaston = new Friend("Gaston");
    Bower b1 = new Bower(alphonse, gaston);
    Bower b2 = new Bower(gaston, alphonse);
    b1.start();
    b2.start();
  }
}
