java死鎖
阿新 • • 發佈:2022-01-15
死鎖
多個執行緒各自戰友一些資源,並且相互等待其他執行緒佔有的資源才能執行,而導致兩個或者多個執行緒都在等待對方釋放資源,都停止執行的情形。某一個同步塊同時擁有兩個以上物件的鎖時,就可能會發生死鎖問題。
形成死鎖的四個必要條件:
- 互斥條件
- 請求與保持條件
- 不剝奪條件
- 迴圈等待條件
避免死鎖:破壞形成死鎖的四個必要條件其中任意一個就可以避免死鎖的產生
package com.yuanyu.thread; //死鎖:多個物件持有對方需要的資源 相互僵持 public class DeadLock { public static void main(String[] args) { Makeup g1=new Makeup("xiaoming",0); Makeup g2=new Makeup("xiaohong",1); g1.start(); g2.start(); } } class LipStick{ } class Mirror{ } class Makeup extends Thread{ String name; int choice; Makeup(String name,int choice){ this.choice=choice; this.name=name; } //需要的資源只有一份,用static來保證資源的唯一 static LipStick lipStick =new LipStick(); static Mirror mirror =new Mirror(); @Override public void run() { //化妝 makeup(); } private void makeup(){ if (choice==0){ synchronized (lipStick){ System.out.println(this.name+"獲得了口紅的鎖"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }synchronized (mirror){ System.out.println(this.name+"獲得了鏡子的鎖"); } } } else { synchronized (mirror){ System.out.println(this.name+"獲得了鏡子的鎖"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }synchronized (lipStick){ System.out.println(this.name+"獲得了口紅的鎖"); } } } } }
程式形成死鎖:
package com.yuanyu.thread; //死鎖:多個物件持有對方需要的資源 相互僵持 public class DeadLock { public static void main(String[] args) { Makeup g1=new Makeup("xiaoming",0); Makeup g2=new Makeup("xiaohong",1); g1.start(); g2.start(); } } class LipStick{ } class Mirror{ } class Makeup extends Thread{ String name; int choice; Makeup(String name,int choice){ this.choice=choice; this.name=name; } //需要的資源只有一份,用static來保證資源的唯一 static LipStick lipStick =new LipStick(); static Mirror mirror =new Mirror(); @Override public void run() { //化妝 makeup(); } private void makeup(){ if (choice==0){ synchronized (lipStick){ System.out.println(this.name+"獲得了口紅的鎖"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (mirror){ System.out.println(this.name+"獲得了鏡子的鎖"); } } else { synchronized (mirror){ System.out.println(this.name+"獲得了鏡子的鎖"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (lipStick){ System.out.println(this.name+"獲得了口紅的鎖"); } } } }
程式執行結果:死鎖問題解決