为了账号安全,请及时绑定邮箱和手机立即绑定

关于多线程的死锁问题,我想写一个死锁的程序,我什么我的两个程序,一个可以锁成功,另一个却不会

关于多线程的死锁问题,我想写一个死锁的程序,我什么我的两个程序,一个可以锁成功,另一个却不会

慕勒3428872 2019-01-19 21:21:46
第一份代码,可以锁成功 public class Main{ public static void main(String[] args){ LockThread lock1 = new LockThread(true); LockThread lock2 = new LockThread(false); Thread thread1 = new Thread(lock1); Thread thread2 = new Thread(lock2); thread1.start(); thread2.start(); } } class LockThread implements Runnable{ private boolean flag; public LockThread(boolean flag){ this.flag = flag; } public void run(){ if (flag){ synchronized(MyLock.lock1){ System.out.println("锁住Lock1"); synchronized(MyLock.lock2){ System.out.println("锁住Lock2"); } } }else{ synchronized(MyLock.lock2){ System.out.println("锁住Lock2"); synchronized(MyLock.lock1){ System.out.println("锁住Lock1"); } } } } } class MyLock{ public static final Object lock1 = new Object(); public static final Object lock2 = new Object(); } 第二份代码,锁不成功public class Money { public void say(){ System.out.println("你给我钱,我给你笔记本电脑!"); } } public class Notebook { public void say(){ System.out.println("你给我电脑,我给你钱"); } } import java.util.concurrent.locks.Lock; public class LockThread implements Runnable{ private boolean flag; private Notebook hp; private Money rmb; public LockThread(Notebook hp, Money rmb, Boolean flag){ this.hp = hp; this.flag = flag; this.rmb = rmb; } public void setFlag(boolean flag) { this.flag = flag; } public Notebook getHp() { return hp; } public void setHp(Notebook hp) { this.hp = hp; } public void setRmb(Money rmb) { this.rmb = rmb; } public Money getRmb() { return rmb; } public boolean isFlag() { return flag; } @Override public void run() { if (flag){ synchronized(hp){ hp.say(); synchronized (rmb){ rmb.say(); } } }else { synchronized (rmb){ rmb.say(); synchronized (hp){ hp.say(); } } } } } public class Main { public static void main(String[] args){ Money rmb = new Money(); Notebook hp = new Notebook(); LockThread lock1 = new LockThread(hp, rmb, true); LockThread lock2 = new LockThread(hp, rmb, false); Thread thread1 = new Thread(lock1); Thread thread2 = new Thread(lock2); thread1.start(); thread2.start(); } }
查看完整描述

1 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

按道理来说,你第二份代码是可能出现死锁的
你没出现死锁可能是因为thread1thread2早申请到了rmb,因为thread1.start()thread2.start()早开始

查看完整回答
反对 回复 2019-02-12
  • 1 回答
  • 0 关注
  • 461 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信