package suo;public class DeadLockTest implements Runnable{ PRivate int flag; static Object o1 = new Object(), o2 = new Object(); //靜態的對象,被DeadLockTest的所有實例對象所公用 public void run(){ System.out.println(flag); if(flag == 0){ synchronized(o1){ try{ Thread.sleep(500); } catch(Exception e){ e.printStackTrace(); } synchronized(o2){ } } } if(flag == 1){ synchronized(o2){ try{ Thread.sleep(500); } catch(Exception e){ e.printStackTrace(); } synchronized(o1){ } } } } public static void main(String[] args){ DeadLockTest test1 = new DeadLockTest(); DeadLockTest test2 = new DeadLockTest(); test1.flag = 1; test2.flag = 0; Thread thread1 = new Thread(test1); Thread thread2 = new Thread(test2); thread1.start(); thread2.start(); } }/*解釋:在main方法中,實例化了兩個實現了Runnable接口的DeadLockTest對象test1和test2,test1的flag等于1,所以在thread1線程執行的時候執行的是run()方法后半部分的代碼,test2的flag等于2,所以在thread2線程啟動的時候執行的是run()方法前半部分的代碼,此時,出現了下列現象:thread1線程占有了o1對象并等待o2對象,而thread2線程占有了o2對象并等待o1對象,而o1和o2又被這倆個線程所共享,所以就出現了死鎖的問題了。*/
新聞熱點
疑難解答