多线程之:死锁

死锁指两个或者多个线程持有锁的同时并等待对方持有的锁,导致无限期等待的情况,通常发生于以不同顺序请求同一组锁。

两个线程以不同顺序获取一组锁会导致死锁,如:

 1 public class DeadLockTest {
 2 
 3     public static class LockGroup{
 4         private  Object objA=new Object();
 5         private  Object objB=new Object();
 6         public  Object getObjA() {
 7             return objA;
 8         }
 9         public Object getObjB() {
10             return objB;
11         }
12         
13     }
14     
15     public static void main(String[] args) throws Exception {
16         final LockGroup group=new LockGroup();
17         Thread threadA=new Thread(new  Runnable() {
18             public void run() {
19                 synchronized (group.getObjA()) {
20                     System.out.println("try to get lockb......");
21                     synchronized (group.getObjB()) {
22                         System.out.println("get all locks now......");
23                     }
24                 }
25             }
26         });
27         Thread threadB=new Thread(new  Runnable() {
28             public void run() {
29                 synchronized (group.getObjB()) {
30                     System.out.println("try to get locka......");
31                     synchronized (group.getObjA()) {
32                         System.out.println("get all locks now......");
33                     }
34                 }
35             }
36         });
37         threadA.start();
38         threadB.start();
39         threadA.join();
40         threadB.join();//将会发生死锁
41     }
42 }

 

posted on 2015-11-29 22:03  jessezeng  阅读(300)  评论(0编辑  收藏  举报

导航