标签: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) { //锁定o2 22 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= 1 46 flag= 0 47 两个线程产生死锁,synchronized的输出语句未被执行。 48 */ 49 50 }
SummerVocation_Learning--java的线程死锁
标签:div sys lock print style syn tac try deadlock
原文地址:https://www.cnblogs.com/DSYR/p/9329423.html