死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致俩个或者多个线程都在等待对方释放资源。

package syn;

public class DeadLock {
    public static void main(String[] args) {
        Makeup s1 = new Makeup(0,"小明");
        Makeup s2 = new Makeup(1,"小红");
        s1.start();
        s2.start();
    }
}
class Lipstick {

}
class Mirror {

}
class Makeup extends Thread{
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();
    int choice;
    String name;
    Makeup(int choice, String name){
        this.choice = choice;
        this.name = name;
    }
    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private void makeup() throws InterruptedException {
        if(choice == 0){
            synchronized (lipstick){
                System.out.println(this.name+"拿到了口红的锁");
                Thread.sleep(1000);
                synchronized (mirror){
                    System.out.println(this.name+"拿到了镜子的锁");
                }
            }
        }else {
            synchronized (mirror){
                System.out.println(this.name+"拿到了镜子的锁");
                Thread.sleep(2000);
                synchronized (lipstick){
                    System.out.println(this.name+"拿到了口红的锁");
                }
            }
        }
    }
}

image
只要将一把锁改为俩把锁就可以释放资源

package syn;

public class DeadLock {
    public static void main(String[] args) {
        Makeup s1 = new Makeup(0,"小明");
        Makeup s2 = new Makeup(1,"小红");
        s1.start();
        s2.start();
    }
}
class Lipstick {

}
class Mirror {

}
class Makeup extends Thread{
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();
    int choice;
    String name;
    Makeup(int choice, String name){
        this.choice = choice;
        this.name = name;
    }
    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private void makeup() throws InterruptedException {
        if(choice == 0){
            synchronized (lipstick){
                System.out.println(this.name+"拿到了口红的锁");
                Thread.sleep(1000);

                }
                synchronized (mirror){
                System.out.println(this.name+"拿到了镜子的锁");
            }

        }else {
            synchronized (mirror){
                System.out.println(this.name+"拿到了镜子的锁");
                Thread.sleep(2000);

            }
            synchronized (lipstick){
                System.out.println(this.name+"拿到了口红的锁");
        }
        }
    }
}

image

posted @ 2024-04-17 20:54  纲炮  阅读(12)  评论(0)    收藏  举报