为什么此代码不能用作死锁? [关闭]

问题描述 投票:-1回答:1
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();

  }
}
multithreading deadlock runnable synchronized
1个回答
0
投票

您的代码只有在返回t2调用后,才能启动a.bar(b)线程。它从不尝试同时调用两个bar()方法。尝试切换最后两行:先呼叫t2.start(),然后

然后

呼叫a.bar(b)
如果不起作用,那么可以尝试:

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

主线程中的短sleep()调用将使t2线程有更多的启动时间,并实际上进入了b.bar(a)调用。
© www.soinside.com 2019 - 2024. All rights reserved.