package com.state;
import org.omg.PortableServer.THREAD_POLICY_ID;
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0,"王子");
Makeup makeup2 = new Makeup(1,"灰姑娘");
makeup.start();
makeup2.start();
}
}
//口红 Lipstick
//创建两个对象
class Lipstick{}
//镜子 mirror
class Mirror{}
//创建个Makeup类继承Thread
class Makeup extends Thread{
static Lipstick lipstick = new Lipstick(); //static只执行一次 new
static Mirror mirror = new Mirror();
int choice;//选择
String qirlName;//使用化妆品的人
//有参
public Makeup(int choice,String qirlName){
this.choice=choice;
this.qirlName=qirlName;
}
//重新run方法
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
}
}
//化妆互相有对方的锁,就是需要获取对方的资源
private void makeup() throws InterruptedException {
if (choice==0){
synchronized (lipstick){//获取口红的锁 synchronized
//输出谁获取口红的锁
System.out.println(this.qirlName+"获得口红的锁");
//休眠
Thread.sleep(1000);
synchronized (mirror){//获取镜子的锁 synchronized
//输出谁获得镜子的锁
System.out.println(this.qirlName+"获得镜子的锁");
//休眠
Thread.sleep(2000);
}
}
}else{
synchronized (mirror){
System.out.println(this.qirlName+"获得镜子锁");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(this.qirlName+"获得口红的锁");
Thread.sleep(2000);
}
}
}
}
}