死锁


死锁

  • 互斥条件:一个资源每次只能被一个进程使用

  • 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放

  • 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺

  • 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系

package thread;
//死锁:多个线程相互相抱着对方需要的资源,然后形成僵持
public class DeadLock {

   public static void main(String[] args) {
       Makeup q1 = new Makeup(0,"白雪公主");
       Makeup q2 = new Makeup(1,"灰姑娘");
       q1.start();
       q2.start();

  }

}
//口红
class Lipstick{

}
//镜子
class Mirror{

}
//化妆
class Makeup extends Thread{
   //需要的资源只有一份,用static来保证只有一份
   static Lipstick lipstick = new Lipstick();
   static Mirror mirror = new Mirror();

   int choice;//选择
   String qirlNmae;//使用化妆品的人
   Makeup(int choice,String qirlNmae){
       this.choice = choice;
       this.qirlNmae = qirlNmae;
  }

   @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.qirlNmae+"获得口红的锁");
               Thread.sleep(1000);
               synchronized (mirror){
                   System.out.println(this.qirlNmae+"获得镜子的锁");
              }
          }
      }else{
           synchronized (mirror){
               System.out.println(this.qirlNmae+"获得镜子的锁");
               Thread.sleep(2000);
               synchronized (qirlNmae){
                   System.out.println(this.qirlNmae+"获得口红的锁");
              }
          }
      }
  }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM