视频地址:https://www.ixigua.com/6915051241223488015

  1. 互斥条件:一个资源每次只能被一个进程使用
  2. 请求与保持:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
  3. 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺。
  4. 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

本节介绍线程死锁,死锁的代码示例说明。怎么避免死锁,死锁的4个必要条件。

什么是死锁?

死锁是指多个线程竞争资源造成相互阻塞的现象

Untitled

public class DeadLock{
    private static Object resource1 = new Object();
    private static Object resource2 = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (resource1) {
                System.out.println(Thread.currentThread() + "得到资源1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + "等待资源2");
                synchronized (resource2) {
                    System.out.println(Thread.currentThread() + "得到资源2");
                }
            }
        }, "线程 1").start();

        new Thread(() -> {
            synchronized (resource2) {
                System.out.println(Thread.currentThread() + "得到资源2");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + "等待资源1");
                synchronized (resource1) {
                    System.out.println(Thread.currentThread() + "得到资源1");
                }
            }
        }, "线程 2").start();
    }
}

运行结果