码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA经典题--死锁案例

时间:2018-05-17 00:54:50      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:bsp   []   lag   zed   tst   thread   read   catch   std   

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

例子程序:

 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经典题--死锁案例

标签:bsp   []   lag   zed   tst   thread   read   catch   std   

原文地址:https://www.cnblogs.com/Kingram/p/9048862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!