Deadlock detection in Java

后端 未结 16 1073
野的像风
野的像风 2020-11-28 20:21

Long time ago, I saved a sentence from a Java reference book: \"Java has no mechanism to handle deadlock. it won\'t even know deadlock occurred.\" (Head First Java 2nd E

16条回答
  •  臣服心动
    2020-11-28 20:48

    After so long, i am able to write the simplest example of Deadlock. Comments are welcome.

    Class A
    {
      synchronized void methodA(B b)
      {
        b.last();
      }
    
      synchronized void last()
      {
        SOP(“ Inside A.last()”);
      }
    }
    
    Class B
    {
      synchronized void methodB(A a)
      {
        a.last();
      }
    
      synchronized void last()
      {
        SOP(“ Inside B.last()”);
      }
    }
    
    
    Class Deadlock implements Runnable 
    {
      A a = new A(); 
      B b = new B();
    
      // Constructor
      Deadlock()
      {
        Thread t = new Thread(); 
        t.start();
        a.methodA(b);
      }
    
      public void run()
      {
        b.methodB(a);
      }
    
      public static void main(String args[] )
      {
        new Deadlock();
      }
    }
    

提交回复
热议问题