package com.Java;
//死锁案例 互相持有对方的锁 并且想要拿到对方的资源
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0, "灰姑凉");
Makeup makeup1 = new Makeup(1, "白雪公主");
makeup.start();
makeup1.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) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (mirror) { //拿镜子
System.out.println(this.girlName + "拿到了镜子");
Thread.sleep(2000);//不让他马上拿口红 模拟延时
synchronized (lipstick) {
//拿完镜子再拿口红 现在口红在另一个人手上 另一个人想要镜子 但镜子在我手上 谁也不让
System.out.println(this.girlName + "拿到了口红");
//解决方法 将这个锁拿出来就行
}
}
} else {
synchronized (lipstick) { //拿口红
System.out.println(this.girlName + "拿到了口红");
Thread.sleep(1000);
synchronized (mirror) {
System.out.println(this.girlName + "拿到了镜子");
}
}
}
}
}