title: Deadlock - how does it happen in this example?
body: <p>can anyone explain:</p>
  <ol>
  <li>why do we  get a deadlock?</li>
  <li>how can Gaston enter function bow before Alphonse exit that function? (it should return from function <code>bowBack()</code> in order to exit the function <code>bow()</code> - or)?</li>
  </ol>
  <p>This is the output I get - and then program is stuck!</p>
  <blockquote>
  <p>Alphonse: Gaston  has bowed to me!</p>
  <p>Gaston: Alphonse  has bowed to me!</p>
  </blockquote>
  <pre><code>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(&quot;%s: %s&quot;
                  + &quot;  has bowed to me!%n&quot;, 
                  this.name, bower.getName());
              bower.bowBack(this);
          }
          public synchronized void bowBack(Friend bower) {
              System.out.format(&quot;%s: %s&quot;
                  + &quot; has bowed back to me!%n&quot;,
                  this.name, bower.getName());
          }
      }
   
      public static void main(String[] args) {
          final Friend alphonse = new Friend(&quot;Alphonse&quot;);
          final Friend gaston = new Friend(&quot;Gaston&quot;);
  
          new Thread(new Runnable() {
              public void run() { alphonse.bow(gaston); }
          }).start();
          new Thread(new Runnable() {
              public void run() { gaston.bow(alphonse); }
          }).start();
      }
  } 
  </code></pre>