javaSE21/10/7
阿新 • • 發佈:2021-10-07
多執行緒
死鎖
- 多個執行緒互相持有對方需要的資源,然後形成僵持
public class DeadLock { public static void main(String[] args) { Makeup makeup = new Makeup(0,"莉莉"); Makeup makeup1 = new Makeup(1,"紅紅"); makeup.start(); makeup1.start(); } } class Lipstick{//口紅 } class Mirror{//鏡子 } class Makeup extends Thread{ //需要的資源只有一份,用static保證 static Lipstick l = new Lipstick(); static Mirror m = new Mirror(); int choice; String girlNmae; public Makeup(int choice,String girlNmae){ this.choice=choice; this.girlNmae=girlNmae; } @Override public void run() { makeUp(); } private void makeUp(){ //化妝:互相持有對方的鎖,即需要拿到對方的資源 if (choice==0){ synchronized (l){//獲得口紅的鎖 System.out.println(this.girlNmae+"獲得口紅的鎖"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } //一個物件先將拿到的鎖釋放再拿別的物件的鎖,就不會出現死鎖 synchronized (m){//一秒後再獲得鏡子的鎖 System.out.println(this.girlNmae+"獲得鏡子的鎖"); } }else{ synchronized (m){//獲得鏡子的鎖 System.out.println(this.girlNmae+"獲得鏡子的鎖"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //一個物件先將拿到的鎖釋放再拿別的物件的鎖,就不會出現死鎖 } synchronized (l){//一秒後獲得口紅的鎖 System.out.println(this.girlNmae+"獲得口紅的鎖"); } } } }
Lock
- 更強大的執行緒同步機制——通過顯示定義同步鎖隨想來實現同步。用Lock物件