相互资源竞争带来恶性循环

[2021-10-07 周四 20:06]

public class TestLOck {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0,"灰姑娘");
        Makeup g2 = new Makeup(1,"白雪公主");

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

//口红
class Lipstick{

}

// 镜子
class Mirror{

}


class Makeup extends Thread{

    //需要的资源只有一份
    static Lipstick lip = new Lipstick();
    static Mirror mir = new Mirror();

    //
    int choice ; //选择
    String girlName ; //使用化妆品的人

    Makeup(int choice, String girlName){
        this.choice = choice;
        this.girlName =girlName;
    }
    @Override
    public void run() {
        makeUp();
    }

    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeUp(){
        if (choice==0) {
            synchronized(lip){//获得了口红的锁
                System.out.println(this.girlName+"获得口红的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 1s钟想获得镜子
                synchronized(mir){
                    System.out.println(this.girlName+"获得镜子的锁");
                }
            }
            //死锁了,相互抱住对方的锁
        }else{

            synchronized(mir){ //获得了镜子的锁
                System.out.println(this.girlName+"获得镜子的锁");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 2s钟想获得镜子
                synchronized(lip){
                    System.out.println(this.girlName+"获得口红的锁");
                }
            }
        }
    }
}
Related
叶昭良
叶昭良
Engineer of offshore wind turbine technique research

My research interests include distributed energy, wind turbine power generation technique , Computational fluid dynamic and programmable matter.