Search code examples
multithreadingdeadlockrunnablesynchronized

Why this code is not working as Deadlock?


class A {

  synchronized void bar(B b) {

    Thread t = Thread.currentThread();
    System.out.println("Entered In A "+t);

    try{
      Thread.sleep(1000);
    }
    catch(Exception e) {
    }
    System.out.println("A trying to enter B");
    b.last();
  }

  synchronized void last() {

      System.out.println("Inside A last");

 }
}


class B {

   synchronized void bar(A a) {

    Thread t = Thread.currentThread();
    System.out.println("Entered In B "+t);
    try{
      Thread.sleep(1000);
    }
    catch(Exception e) {
    }
     System.out.println("B trying to enter A");
     a.last();
  }

  synchronized void last() {

    System.out.println("Inside B last");

  }
}

class Main {

  public static void main(String[] args) {

      A a = new A();
      B b = new B();
      // Thread t1 = new Thread(){
      //   public void run() {
      //     a.bar(b);
      //   }
      // };
      Thread t2 = new Thread() {
        public void run() {
          b.bar(a);
        }
      };
      System.out.println("Initialization :");
     // t1.start();
      a.bar(b);
      t2.start();

  }
}

Solution

  • Your code doesn't start the t2 thread until after the a.bar(b) call has returned. It never tries to call both bar() methods concurrently.

    Try switching those last two lines: Call t2.start() first, and then call a.bar(b).


    If that doesn't work, then maybe try:

    t2.start();
    try { sleep(100); } catch {...}
    a.bar(b);
    

    The short sleep() call in the main thread will give the t2 thread more time to start up and actually enter the b.bar(a) call.