JAVA经典题--死锁案例

死锁原理: 两个线程相互等待对方释放同步监视器

例子程序:

 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 }

 

    原文作者:Kingram
    原文地址: http://www.cnblogs.com/Kingram/p/9048862.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞