练习题之死锁

public class PrintMain {
  public static String obj1="obj1";
  public static String obj2="obj2";

  public static void main(String[] args) {
    
    new Thread(new Runnable() {
      public void run() {
        System.out.println(new Date().toString + "LockA开始执行");
        while(true) {
           synchronized(obj1) {
                 System.out.println(new Date().toString + "LockA锁住obj1");
                 Thread.sleep(3000);
                  synchronized(obj2) {
                      System.out.println(new Date().toString + "LockA锁住obj2");
                      Thread.sleep(60*1000);
                   }
            }
        }
      }   
    },"LockA").start();
    

   new Thread(new Runnable() {
      public void run() {
        System.out.println(new Date().toString + "LockB开始执行");
        while(true) {
           synchronized(obj2) {
                 System.out.println(new Date().toString + "LockB锁住obj2");
                 Thread.sleep(3000);
                  synchronized(obj1) {
                      System.out.println(new Date().toString + "LockB锁住obj1");
                      Thread.sleep(60*1000);
                   }
            }
        }
      }   
    },"LockB").start();

  }
}

 

posted @ 2016-04-12 23:26  moonandstar08  阅读(424)  评论(0编辑  收藏  举报