模拟死锁

public class MyClass {
    private static Object resourceA = new Object();
    private static Object resourceB = new Object();
    
    public static void main(String args[]) {
      Thread threadA = new Thread( new Runnable() {
          public void run() {
              System.out.println(Thread.currentThread() + " getting A");
              synchronized (resourceA) {
                  System.out.println(Thread.currentThread() + " got A");
                  try {
                      Thread.sleep(1000);
                  } catch(InterruptedException e) {
                      e.printStackTrace();
                  }
                  
                  
                  System.out.println(Thread.currentThread() + " getting B");
                  synchronized (resourceB) {
                      System.out.println(Thread.currentThread() + " got B");
                      try {
                          Thread.sleep(1000);
                      } catch(InterruptedException e) {
                          e.printStackTrace();
                      }
                      
                  }
                  
              }
              
              
          }
      } );
      
      Thread threadB = new Thread( new Runnable() {
          public void run() {
              
              System.out.println(Thread.currentThread() + " getting B");
              synchronized (resourceB) {
                  System.out.println(Thread.currentThread() + " got B");
                  try {
                      Thread.sleep(1000);
                  } catch(InterruptedException e) {
                      e.printStackTrace();
                  }
                  
                  
                  System.out.println(Thread.currentThread() + " getting A");
                  synchronized (resourceA) {
                      System.out.println(Thread.currentThread() + " got A");
                      try {
                          Thread.sleep(1000);
                      } catch(InterruptedException e) {
                          e.printStackTrace();
                      }
                      
                  }
                  
              }
              
              
              
              
          }
      } );
      
      
      threadA.start();
      threadB.start();
    }
}

 

posted @ 2021-12-18 17:44  Ready!  阅读(42)  评论(0编辑  收藏  举报