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 }

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

转载于:https://www.cnblogs.com/dennisac/archive/2012/03/13/2394375.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值