JAVA實現的一個簡單的死鎖(附解釋)

[java] view plain copy
  1. public class DeadLockTest implements Runnable{  
  2.  private int flag;  
  3.  static Object o1 = new Object(), o2 = new Object();      //靜態的對象,被DeadLockTest的所有實例對象所公用  
  4.    
  5.  public void run(){  
  6.     
  7.   System.out.println(flag);  
  8.   if(flag == 0){  
  9.    synchronized(o1){  
  10.     try{  
  11.      Thread.sleep(500);  
  12.     } catch(Exception e){  
  13.      e.printStackTrace();  
  14.     }  
  15.     synchronized(o2){  
  16.     }  
  17.    }   
  18.   }  
  19.   if(flag == 1){  
  20.    synchronized(o2){  
  21.     try{  
  22.      Thread.sleep(500);  
  23.     } catch(Exception e){  
  24.      e.printStackTrace();  
  25.     }  
  26.     synchronized(o1){  
  27.     }  
  28.    }   
  29.   }   
  30.  }  
  31.    
  32.  public static void main(String[] args){  
  33.   DeadLockTest test1 = new DeadLockTest();  
  34.   DeadLockTest test2 = new DeadLockTest();  
  35.   test1.flag = 1;  
  36.   test2.flag = 0;  
  37.   Thread thread1 = new Thread(test1);  
  38.   Thread thread2 = new Thread(test2);  
  39.   thread1.start();  
  40.   thread2.start();  
  41.  }  
  42. }  
  43.   
  44.    
  45.   
  46. 解釋:在main方法中,實例化了兩個實現了Runnable接口的DeadLockTest對象test1和test2,test1的flag等於1,所以在thread1線程執行的時候執行的是run()方法後半部分的代碼,test2的flag等於2,所以在thread2線程啓動的時候執行的是run()方法前半部分的代碼,此時,出現了下列現象:thread1線程佔有了o1對象並等待o2對象,而thread2線程佔有了o2對象並等待o1對象,而o1和o2又被這倆個線程所共享,所以就出現了死鎖的問題了。  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章