如下,我们定义了两个资源,创建了两个线程,每个线程都持有一个资源,并请求一个被另外一个线程所持有的资源,故陷入僵持状态,两个线程发生死锁。
public class DeadLockTest {
public static final Object resource1 = new Object();
public static final Object resource2 = new Object();
public static void main(String[] args) {
new Thread(() -> {
synchronized (resource1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":等待");
synchronized (resource2) {
System.out.println(Thread.currentThread().getName() + ":可以执行");
}
}
}, "A").start();
new Thread(() -> {
synchronized (resource2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":等待");
synchronized (resource1) {
System.out.println(Thread.currentThread().getName() + ":可以执行");
}
}
}, "B").start();
}
}
多个进程或者线程可以竞争有限数量的资源。两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。
{P0, P1,..., Pn}, P0 等待的资源被 P1 占有,P1 等待的资源被 P2 占有,…,Pn-1 等待的资源被 Pn 占有,Pn 等待的资源被 P0 占有。解决死锁的方法可以从多个角度去分析,一般的情况下,有预防,避免,检测和解除四种。