Multithreading 为什么这段代码不是死锁?

Multithreading 为什么这段代码不是死锁?,multithreading,deadlock,runnable,synchronized,Multithreading,Deadlock,Runnable,Synchronized,在a.bar(b)调用返回之前,代码不会启动t2线程。它从不同时调用两个bar()方法 尝试切换最后两行:首先调用t2.start(),然后调用a.bar(b) 如果这不起作用,那么可以尝试: class A { synchronized void bar(B b) { Thread t = Thread.currentThread(); System.out.println("Entered In A "+t); try{ Thread.slee

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

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


如果这不起作用,那么可以尝试:

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

  }
}

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

切换两行操作有效。因此,我可以得出结论,主线程已经启动,因此它首先到达bar(),然后第二个线程启动,因此在任何时候,两个线程都不会同时调用bar。
t2.start();
try { sleep(100); } catch {...}
a.bar(b);