模拟开两道门的场景
线程任务类
public class DeadLock implements Runnable{
//线程共享的成员变量
private int number=0;
//定义两把钥匙
private String oneKey="钥匙1";
private String twoKey="钥匙2";
@Override
public void run() {
while (true) {
if (number % 2 == 0) {
synchronized (oneKey) {
String name = Thread.currentThread().getName();
System.out.println(name + "拿到了" + oneKey + ",等待" + twoKey);
synchronized (twoKey) {
System.out.println(name + "开门到家里了");
}
}
} else {
synchronized (twoKey) {
String name = Thread.currentThread().getName();
System.out.println(name + "拿到了" + twoKey + ",等待" + oneKey);
synchronized (oneKey) {
System.out.println(name + "出门去玩了");
}
}
}
number++;
}
}
}
测试类
public class TestLock {
public static void main(String[] args) {
//创建线程任务
DeadLock dl = new DeadLock();
//模拟多人开门
Thread t1 = new Thread(dl, "1号特工");
Thread t2 = new Thread(dl, "2号特工");
t1.start();
t2.start();
}
运行结果:
分析:开始2号特工线程先拿到cpu的执行权,并且在顺利拿到第一把钥匙后,有顺利拿到了第二把钥匙,然后2号特工失去了cpu的执行权,这时1号特工进了if条件,拿到第一把钥匙,然后1号特工失去了cpu的执行权,这是2号特工拿到了cpu的执行权,进行number++,number变成1,进入else条件,拿到第二把钥匙,正当2号特工准备拿第一把钥匙时,在前面已经被1号特工拿到了,然而1号特工又在准备拿第二把钥匙,然后两个特工都在拿对应的另一把钥匙,互不相让,进的进不去,出的出不去,就造成了死锁的现象,程序就不动了。(这里说的是某种极端现象,程序每次运行的结果都不同,但是最终的结果都是一样的)。