Posted on 2008-12-06 11:54
鱼跃于渊 阅读(206)
评论(0) 编辑 收藏 所属分类:
j2se
1
2 public class ThreadDeadLock implements Runnable{
3
4 private int flag ;
5 static Object o1 = new Object() ;
6 static Object o2 = new Object() ;
7
8 public void run(){
9 System.out.println("flag = " + flag) ;
10 if(flag==1){
11 synchronized(o1){
12 try{
13 Thread.sleep(1000) ;
14 }catch(InterruptedException ex){
15 ex.printStackTrace() ;
16 }
17 synchronized(o2){
18 System.out.println("Hello , I'm Thread t1, and I synchronized o2 !");
19 }
20 }
21
22 }
23
24 if(flag==2){
25 synchronized(o2){
26 try{
27 Thread.sleep(1000);
28 }catch(InterruptedException ex){
29 ex.printStackTrace() ;
30 }
31 synchronized(o1){
32 System.out.println("Hello , I'm Thread t2, and I synchronized o1 !") ;
33 }
34 }
35
36 }
37 }
38
39 public static void main(String[] args){
40 ThreadDeadLock dl1 = new ThreadDeadLock() ;
41 ThreadDeadLock dl2 = new ThreadDeadLock() ;
42 dl1.flag = 1 ;
43 dl2.flag = 2 ;
44 Thread t1 = new Thread(dl1) ;
45 Thread t2 = new Thread(dl2) ;
46 t1.start() ;
47 t2.start() ;
48 }
49 }