public class DieLock implements Runnable {
//创建两把锁
private static final Object lockA = new Object();
private static final Object lockB = new Object();
private boolean flag;
public DieLock(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if(flag){
synchronized (lockA){
System.out.println(Thread.currentThread().getName()+" is using lockA");
synchronized (lockB){
System.out.println(Thread.currentThread().getName()+" is using lockB");
}
System.out.println(Thread.currentThread().getName()+" lost lockB");
}
System.out.println(Thread.currentThread().getName()+" lost lockA");
}else{
synchronized (lockB){
System.out.println(Thread.currentThread().getName()+" is using lockB");
synchronized (lockA){
System.out.println(Thread.currentThread().getName()+" is using lockA");
}
System.out.println(Thread.currentThread().getName()+" lost lockA");
}
System.out.println(Thread.currentThread().getName()+" lost lockB");
}
}
}
public class Test {
public static void main(String[] args) {
DieLock target1 = new DieLock(true);
DieLock target2 = new DieLock(false);
Thread thread1 = new Thread(target1);
thread1.setName("thread1");
Thread thread2 = new Thread(target2);
thread2.setName("thread2");
thread1.start();
thread2.start();
}
}
理想结果:
死锁结果: