java 张三和李四的死锁

 1 class ZhangSan{
2 public void say(){
3 System.out.println("Zhang said:you should lend your painting to me!");
4 }
5 public void get(){
6 System.out.println("Zhang has got it!");
7 }
8 }
9 class LiSi{
10 public void say(){
11 System.out.println("Li said:you should lend your book to me!");
12 }
13 public void get(){
14 System.out.println("Li has got it!");
15 }
16 }
17 public class DeadLock implements Runnable{
18 private static ZhangSan zs=new ZhangSan();
19 private static LiSi ls=new LiSi();
20 private boolean flag=false;
21 public void run(){
22 if(flag){
23 synchronized (zs){
24 zs.say();
25 try{
26 Thread.sleep(500);
27 }catch (InterruptedException e){
28 e.printStackTrace();
29 }
30 synchronized (ls){
31 zs.get();
32 }
33 }
34 }else{
35 synchronized (ls){
36 ls.say();
37 try{
38 Thread.sleep(500);
39 }catch (InterruptedException e){
40 e.printStackTrace();
41 }
42 synchronized (zs){
43 ls.get();
44 }
45 }
46 }
47 }
48 public static void main(String[] args) {
49 DeadLock t1=new DeadLock();
50 DeadLock t2=new DeadLock();
51 t1.flag=true;
52 t2.flag=false;
53 Thread thA=new Thread(t1);
54 Thread thB=new Thread(t2);
55 thA.start();
56 thB.start();
57 }
58 }

从程序中可以看出,两个线程都在等待彼此执行完成,从而死锁。。

posted @ 2012-03-13 20:06  谈笑风生膜法师  阅读(442)  评论(0编辑  收藏  举报