关于多线程的死锁问题,我想写一个死锁的程序,我什么我的两个程序,一个可以锁成功,另一个却不会
第一份代码,可以锁成功
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
按道理来说,你第二份代码是可能出现死锁的
你没出现死锁可能是因为
thread1
比thread2
早申请到了rmb
,因为thread1.start()
比thread2.start()
早开始