title: Confusing output in multithreading shows deadlock?
body: <p>I just compiled and run this program of java but the output is unpleasant.
  I don't know why the threads are in deadlock situation.
  Can anyone help me to understand the output of the program.</p>
  
  <pre><code>class A {
  synchronized void foo(B b) {
      String name=Thread.currentThread().getName();
      System.out.println(name+"entered A.foo");
  
      try {
          Thread.sleep(1000);
      } catch(Exception e) {}
      System.out.println(name+"trying to call B.last()");
      b.last();
  }
  synchronized void last() {
      System.out.println("inside A.last");
  }
  }
  
  class B {
  synchronized void bar(A a) {
      String name=Thread.currentThread().getName();
      System.out.println(name+"entered B.bar");
      try {
          Thread.sleep(1000);
      } catch(Exception e) {
          System.out.println("b interrupted");
      }
      System.out.println(name+"trying to call A.last()");
      a.last();
  }
  synchronized void last() {
      System.out.println("inside A.last");
  }
  }
  
  class DeadLock implements Runnable {
  A a=new A();
  B b=new B();
  DeadLock() {
      Thread.currentThread().setName("mainthread");
      Thread t=new Thread(this,"racingthread");
      t.start();
      a.foo(b);
      System.out.println("back in main thread");
  }
  public void run() {
      b.bar(a);
      System.out.println("back in other theread");
  }
  public static void main(String...d) {
      new DeadLock();
  }
  }
  </code></pre>
  
  <p><strong>the output on my computer is</strong></p>
  
  <pre><code>mainthreadentered A.foo
  
  racingthreadentered B.bar
  
  mainthreadtrying to call B.last()
  
  racingthreadtrying to call A.last()
  </code></pre>