死锁

死锁

public class DeadLock {

    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修饰,保证只有一份资源
    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();
        }
    }
    public void makeUp() throws InterruptedException {
        if (choice == 0){
             synchronized (lipstick){//获得口红的锁
                 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(2000);
                synchronized (lipstick){//获得口红的锁
                    System.out.println(this.girlName + "获得口红");
                }
            }
        }
    }
}

产生死锁的必要条件:

  1. 互斥条件:一个资源只能被一个进程使用。
  2. 请求与保持条件:一个进程因请求资源而阻塞时,对以获得资源保持不放。
  3. 不剥夺条件:进程以获得的资源在未使用完之前不能被强行剥夺。
  4. 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源。

你可能感兴趣的:(死锁)