其他分享
首页 > 其他分享> > 死锁

死锁

作者:互联网

化妆的例子

两个女生同时要化妆,需要用口红和镜子:

package test2;


public class DeadLock {
    public static void main(String[] args) {

        Makeup g1=new Makeup(0,"girl1");
        Makeup g2=new Makeup(1,"gilr2");

        g1.start();
        g2.start();
    }
}

//口红
class LipStick{

}

//镜子
class Mirror{

}

//化妆
class Makeup extends Thread{

    //需要的资源只有一个,用static保证只有一份

    static  LipStick lipStick=new LipStick();
    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(this.choice==0){
            synchronized (lipStick){

                System.out.println(this.girlName+"获得口红的锁");
                sleep(1000);

                synchronized (mirror){
                    System.out.println(this.girlName+"获得镜子的锁");
                }
            }
        }else{

            synchronized (mirror){

                System.out.println(this.girlName+"获得镜子的锁");
                sleep(2000);

                synchronized (lipStick){
                    System.out.println(this.girlName+"获得口红的锁");
                }

        }

    }
}

}

修改代码,使其不会死锁:把嵌套的代码块分离

    private void makeup() throws InterruptedException {
        if(this.choice==0){
            synchronized (lipStick){

                System.out.println(this.girlName+"获得口红的锁");
                sleep(1000);

            }
            synchronized (mirror){
                System.out.println(this.girlName+"获得镜子的锁");
            }
        }else{

            synchronized (mirror){

                System.out.println(this.girlName+"获得镜子的锁");
                sleep(2000);

            }
            synchronized (lipStick){
                System.out.println(this.girlName+"获得口红的锁");
            }

             }
}

标签:girlName,synchronized,口红,System,死锁,println,out
来源: https://www.cnblogs.com/kakafa/p/15001855.html