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

多线程之:死锁

时间:2015-11-29 23:16:00      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 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 }

 

多线程之:死锁

标签:

原文地址:http://www.cnblogs.com/jessezeng/p/5005753.html

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