首页 > 其他分享 >死锁

死锁

时间:2023-03-18 17:45:35浏览次数:44  
标签:girlName synchronized 口红 Makeup choice 死锁 new

package edu.wtbu;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class Demo10 {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"灰姑凉");
Makeup g2 = new Makeup(1,"白雪公主");

g1.start();
g2.start();
}
}

//口红
class LipsTick{

}

//镜子
class Mirror{

}

//化妆
class Makeup extends Thread{
static LipsTick lipsTick=new LipsTick();
static Mirror mirror=new Mirror();
int choice;//选择
String girlName;//使用化妆品的人

public Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}

@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

}

//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if(choice==0){
synchronized (lipsTick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");

}
Thread.sleep(1000);
synchronized (mirror){//一秒钟后获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
}
}else{
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");

}
Thread.sleep(1000);
synchronized (lipsTick){//一秒钟后获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}

标签:girlName,synchronized,口红,Makeup,choice,死锁,new
From: https://www.cnblogs.com/123456dh/p/17231315.html

相关文章