线程 T1 占有A锁的钥匙, 同时需要拿B锁的钥匙.
线程 T2 占有B锁的钥匙, 同时需要拿A锁的钥匙.
如果两个线程都不释放自己的钥匙, 那么就会出现死锁. 如果T1线程很快执行完了, 并释放了自己的资源, 就不会出现死锁.
public class DeadLock {
private static final Object a = new Object();
private static final Object b = new Object();
public static void main(String[] args) throws InterruptedException {
new Thread(new Task(true)).start();
// Thread.sleep(1);
new Thread(new Task(false)).start();
}
static class Task implements Runnable {
private boolean flag;
public Task(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if (flag) {
synchronized (a) {
System.out.println(Thread.currentThread().getName() + "获取到资源a...");
synchronized (b) {
System.out.println(Thread.currentThread().getName() + "获取到资源b...");
}
}
} else {
synchronized (b) {
System.out.println(Thread.currentThread().getName() + "获取到资源b...");
synchronized (a) {
System.out.println(Thread.currentThread().getName() + "获取到资源a...");
}
}
}
}
}
}