为什么此代码不作为死锁工作?

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

  }
}

a.bar(b) 调用返回 之后,您的代码不会启动 t2 线程。它从不尝试同时调用两个 bar() 方法。

尝试切换最后两行:先调用 t2.start(),然后 然后 调用 a.bar(b).


如果还是不行,也许可以试试:

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

主线程中的短 sleep() 调用会给 t2 线程更多的时间来启动并实际进入 b.bar(a) 调用。