標籤:div sys lock print style syn tac try deadlock
1 2 public class Test_DeadLock implements Runnable { 3 4 public int flag = 1; 5 static Object o1 = new Object(),o2 = new Object(); 6 public void run() { 7 System.out.println("flag= " + flag); 8 if (flag == 1) { 9 synchronized (o1) { //o1鎖定10 try {11 Thread.sleep(500);12 } catch (Exception e) {13 e.printStackTrace();14 }15 synchronized (o2) { //只要再鎖定o2,就能列印出1.16 System.out.println("1"); //但是o2被另一個線程鎖定了,所以列印不出1.17 }18 }19 }20 if (flag == 0) {21 synchronized (o2) { //鎖定o222 try {23 Thread.sleep(500);24 } catch (Exception e) {25 e.printStackTrace();26 }27 synchronized (o1) { //只要再等待鎖定o1,就能列印出0.28 System.out.println("0"); //但是o1另一個線程鎖定,無法執行。兩個線程被鎖死,誰都無法完成執行。29 }30 }31 }32 }33 34 public static void main(String[] args) {35 Test_DeadLock t1 = new Test_DeadLock();36 Test_DeadLock t2 = new Test_DeadLock();37 t1.flag = 1;38 t2.flag = 0;39 Thread t11 = new Thread(t1);40 Thread t21 = new Thread(t2);41 t11.start(); t21.start();42 43 }44 /*45 * flag= 146 flag= 047 兩個線程產生死結,synchronized的輸出語句未被執行。48 */49 50 }
SummerVocation_Learning--java的線程死結