话不多说,直接上代码。线程0暂停了50毫秒,是为了感知到死锁,如果你的电脑不卡~不加入这段代码的话无法产生死锁哦。
/**
* @ClassName DeadLockDemo
* @Description TODO 死锁Demo
* @Author CabbageDevil
* @Date 2019/5/28 23:24
* @Version 1.0
**/
public class DeadLockDemo {
/**
* 资源A
*/
private static final Object HAIR_A = new Object();
/**
* 资源B
*/
private static final Object HAIR_B = new Object();
public static void main(String[] args) {
new Thread(() -> {
synchronized (HAIR_A) {
try {
Thread.sleep(50L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (HAIR_B) {
System.out.println("A抓住了B的头发");
}
}
}).start();
new Thread(() -> {
synchronized (HAIR_B) {
synchronized (HAIR_A) {
System.out.println("B抓住了A的头发");
}
}
}).start();
}
}
ps:如何检查是否死锁
https://blog.csdn.net/BCDMW233/article/details/90649841