欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线程死锁问题的解决

程序员文章站 2022-04-17 14:37:13
...

死锁是由于 “同步块需要同时持有多个对象锁造成”的,要解决这个问题,思路很简单, 就是:同一个代码块,不要同时持有两个对象锁

package com.yqq.app12;

/**
 * @Author yqq
 * @Date 2021/11/28 23:14
 * @Version 1.0
 */

import lombok.Setter;

/**
 * 口红类
 */
class Lipstick{

}

/**
 * 镜子类
 */
class Mirror{

}

/**
 * 化妆线程类
 */
@Setter
class Makeup extends Thread{
    private int flag;//flag=0:拿着口红,flag!=0:拿着镜子
    private String girlName;
    static  Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    @Override
    public void run() {
        this.doMakeup();
    }
    /**
     * 开始化妆
     */
    public void doMakeup(){
        if (flag == 0){
            synchronized (lipstick){
                System.out.println(this.girlName+" 拿着口红");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (mirror){
                System.out.println(this.girlName+" 拿着镜子");
            }
        }else {
            synchronized (mirror){
                System.out.println(this.girlName+" 拿着镜子");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (lipstick){
                System.out.println(this.girlName+" 拿着口红");
            }
        }
    }
}
public class DeadLockThread {
    public static void main(String[] args) {
        Makeup makeup = new Makeup();
        makeup.setFlag(0);
        makeup.setGirlName("瓦妮莎");
        Makeup makeup1 = new Makeup();
        makeup1.setFlag(1);
        makeup1.setGirlName("刘亦菲");
        makeup.start();
        makeup1.start();
    }
}

线程死锁问题的解决