java死锁小例子

 4 package cn.com.io.threadDemo.ThreadSyn;
 5 
 6 /**
 7  * 通过两个属性值创建死锁
 8  * 本程序通过两个线程各自锁定一个属性值,这样两个线程都无法结束,造成死锁
 9  * @author Administrator
10  *
11  */
12 public class ThreadSyn2 implements Runnable{
13  
14  private static Object obj1=new Object();
15  
16  private static Object obj2=new Object();
17 
18  /**
19   * @param args
20   */
21  public static void main(String[] args) {
22   ThreadSyn2 ts1=new ThreadSyn2();
23   ThreadSyn2 ts2=new ThreadSyn2();
24   
25   Thread t1=new Thread(ts1);//线程1
26   Thread t2=new Thread(ts2);//线程2
27   t1.setName("theOne");
28   t2.setName("theTwo");
29   
30   t1.start();
31   t2.start();
32 
33  }
34 
35  public void run() {
36   String name=Thread.currentThread().getName();
37   if(name.equals("theOne")){
38    method1(name);
39   }else{
40    method2(name);
41   }
42   
43  }
44 
45  //线程1的方法锁定obj1,线程2就无法完成
46  private void method1(String name) {
47   System.out.println(name);
48   synchronized(obj1){
49    try {
50     Thread.sleep(1000);
51    } catch (InterruptedException e) {
52     e.printStackTrace();
53    }
54    synchronized(obj2){
55     System.out.println(obj2);
56    }   
57   }  
58  }
59 
60     //线程1的方法锁定obj2,线程1就无法完成
61  private void method2(String name) {
62   System.out.println(name);
63   synchronized(obj2){
64    try {
65     Thread.sleep(1000);
66    } catch (InterruptedException e) {
67     e.printStackTrace();
68    }
69    synchronized(obj1){
70     System.out.println(obj1);
71    }
72   }  
73  }
74 }

 

posted on 2014-06-22 16:01  Lishenyin  阅读(173)  评论(0编辑  收藏  举报

导航