概述
互相要对方正在占有的锁,导致卡住不动
实例
/**
* 死锁
*/
public class TestDeadLock {
public static void main(String[] args) {
new MakeUp(0,"嘟嘟").start();
new MakeUp(1,"dudu").start();
}
}
//镜子
class Mirror{
}
//口红
class Lipstick{
}
//化妆
class MakeUp extends Thread{
static Mirror mirror = new Mirror();
static Lipstick lipstick = new Lipstick();
private int select;
private String name;
public MakeUp(int select, String name) {
this.select = select;
this.name = name;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void makeup() throws InterruptedException {
if(select == 0){
synchronized (mirror){
System.out.println(this.name+ " 获得了镜子的锁");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(this.name + " 获得了口红的锁");
}
}
}else{
synchronized (lipstick){
System.out.println(this.name + " 获得了口红的锁");
Thread.sleep(2000);
synchronized (mirror){
System.out.println(this.name+ " 获得了镜子的锁");
}
}
}
}