简单顺序死锁的条件
1、两个线程1,2
2、两个资源a,b
3、两个线程先获取不同的资源(使用Thread.sleep)
demo
package cn.enjoyedu.ch7.safeclass;
/**
* 测试简单顺序死锁
**/
public class TestDeadLock {
static class CustomerA extends Thread{
Object a;
Object b;
public CustomerA(Object a, Object b) {
this.a = a;
this.b = b;
}
@Override
public void run() {
synchronized (a){
try {
System.out.println("CustomerA开始执行,获取了锁a");
Thread.sleep(100);
synchronized (b){
System.out.println("CustomerA执行完成");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class CustomerB extends Thread{
Object a;
Object b;
public CustomerB(Object a, Object b) {
this.a = a;
this.b = b;
}
@Override
public void run() {
synchronized (b){
try {
System.out.println("CustomerB开始执行,获取了锁b");
Thread.sleep(100);
synchronized (a){
System.out.println("CustomerB执行完成");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Object a = new Object();
Object b = new Object();
new CustomerA(a,b).start();
new CustomerB(a,b).start();
}
}
执行结果
CustomerA开始执行,获取了锁a
CustomerB开始执行,获取了锁b
----然后程序就卡住了,不往下执行了