晒太阳

2012年11月23日

java线程互锁演示

 1 /**
 2  * 线程互锁:线程td1得到obj1的锁,线程td2得到了obj2的锁,接着,线程td1在持有obj1的锁的同时
 3  * 企图得到obj2的锁,而此时线程td2仍持有obj2的锁,所以线程td1等待,而线程td2的行为也与线程td1相同
 4  * 因此就形成了死锁
 5  */
 6 public class Client {
 7     public static void main(String[] args) {
 8         final Object obj1 = "test1";
 9         final Object obj2 = "test2";
10         
11         Thread td1 = new Thread(){
12             public void run(){
13                 synchronized(obj1){
14                     System.out.println("td1得到了obj1的锁");
15                     try {
16                         Thread.sleep(1000);
17                     } catch (InterruptedException e) {
18                         e.printStackTrace();
19                     }
20                     
21                     synchronized(obj2){
22                         System.out.println("td1企图得到obj2的锁");
23                         
24                         try {
25                             Thread.sleep(1000);
26                         } catch (InterruptedException e) {
27                             e.printStackTrace();
28                         }
29                     }
30                 }
31             }
32         };
33         
34 
35         Thread td2 = new Thread(){
36             public void run(){
37                 synchronized(obj2){
38                     System.out.println("td2得到了obj2的锁");
39                     try {
40                         Thread.sleep(1000);
41                     } catch (InterruptedException e) {
42                         e.printStackTrace();
43                     }
44                     
45                     synchronized(obj1){
46                         System.out.println("td2企图得到obj1的锁");
47                         
48                         try {
49                             Thread.sleep(1000);
50                         } catch (InterruptedException e) {
51                             e.printStackTrace();
52                         }
53                     }
54                 }
55             }
56         };
57         
58         td1.start();
59         td2.start();
60     }
61 
62 }

posted @ 2012-11-23 06:16 晒太阳 阅读(356) | 评论 (0)编辑 收藏

<2012年11月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

导航

统计

常用链接

留言簿

随笔档案

文章档案

收藏夹

搜索

最新评论

阅读排行榜

评论排行榜