什么是死锁?
多个线程互相抱着对方的资源,然后形成僵持
产生死锁的四个必要条件:
(1)互斥条件:一个资源每次只能被一个进程使用
(2)请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
(3)不剥夺条件:进程已获得的资源,在未使用之前,不能强行剥夺
(4)循环等待条件:若干进程之间形成一种头尾相连的循环等待资源关系
上面列出的四个必要条件,我们只要想办法破其中任意或多个条件,就可以避免死锁的产生
/** * @author DB * @title: DeadLock * @projectName XianCheng * @description: 死锁问题 * @date 2021/11/14 22:25 */ public class DeadLock { public static void main(String[] args) { Makeup g1 = new Makeup(0, "白雪公主"); Makeup g2 = new Makeup(1, "灰姑凉"); g1.start(); g2.start(); } } //口红 class LispStick{ } //镜子 class Mirror{ } class Makeup extends Thread{ //需要的资源只有一份,用static 关键字来保证只有一份 static LispStick lispStick = new LispStick(); static Mirror mirror = new Mirror(); int choice; //选择 String girlName; //使用化妆品的人 Makeup(int choice, String girlName){ this.choice = choice; this.girlName = girlName; } @Override public void run() { //化妆 try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } } private void makeup() throws InterruptedException { if (choice == 0){ synchronized (lispStick){ System.out.println(this.girlName + "获得口红的锁"); Thread.sleep(1000); synchronized (mirror){ System.out.println(this.girlName + "获得镜子的锁"); } } }else { synchronized (mirror){ System.out.println(this.girlName + "获得镜子的锁"); Thread.sleep(1000); synchronized (lispStick){ System.out.println(this.girlName + "获得口红的锁"); } } } } }
程序死锁,直接卡死