死鎖


死鎖

  • 互斥條件:一個資源每次只能被一個進程使用

  • 請求與保持條件:一個進程因請求資源而阻塞時,對已獲得的資源保持不放

  • 不剝奪條件:進程已獲得的資源,在未使用完之前,不能強行剝奪

  • 循環等待條件:若干進程之間形成一種頭尾相接的循環等待資源關系

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