1. 程式人生 > >JAVA經典題--死鎖案例

JAVA經典題--死鎖案例

deadlock bject pre style CA cat lee 子程序 args

死鎖原理: 兩個線程相互等待對方釋放同步監視器

例子程序:

 1 public class TestDeadLock implements Runnable {
 2     
 3     public int flag = 1;
 4     static Object o1 = new Object(), o2 = new Object();
 5 
 6     public void run() {
 7         if (flag == 1) {
 8             synchronized (o1) {
 9                 try {
10                     Thread.sleep(500);
11 } catch (Exception e) { 12 e.printStackTrace(); 13 } 14 synchronized (o2) { 15 System.out.println("1"); 16 } 17 } 18 } 19 if (flag == 0) { 20 synchronized (o2) {
21 try { 22 Thread.sleep(500); 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } 26 synchronized (o1) { 27 System.out.println("0"); 28 } 29 } 30 }
31 } 32 33 public static void main(String[] args) { 34 TestDeadLock td1 = new TestDeadLock(); 35 TestDeadLock td2 = new TestDeadLock(); 36 td1.flag = 1; 37 td2.flag = 0; 38 Thread t1 = new Thread(td1); 39 Thread t2 = new Thread(td2); 40 t1.start(); 41 t2.start(); 42 } 43 }

JAVA經典題--死鎖案例