死锁详细讲解
多個線程占有自己資源還想占用其他線程的資源導致兩個或以上線程停止運行的情況
=====
某一個同步塊同時擁有“兩個以上對象的鎖”時可能發生死鎖
=====
死鎖四個必要條件:
一:
a資源只能被一個進程使用
二:
一個進程阻塞時擁有的a資源不釋放
三:
一個進程擁有的a資源在使用完之前不能搶走
四:
一個線程擁有了a資源又想擁有b資源
只要破壞一個或多個條件就能避免死鎖
======
package com.wuming.thread; //死鎖:多個線程同時抱著對方需要的資源,形成僵持 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;//使用化妝品的人/*** Allocates a new {@code Thread} object. This constructor has the same* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}* {@code (null, null, gname)}, where {@code gname} is a newly generated* name. Automatically generated names are of the form* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.*/public Makeup(int choice, String girlName) {this.choice = choice;this.girlName = girlName;}@Overridepublic void run() {//化妝try {makeup();} catch (InterruptedException e) {e.printStackTrace();}}//化妝,互相持有對方的鎖,就是需要拿到對方的資源private void makeup() throws InterruptedException {if (choice==0){synchronized (lipstick){//獲得口紅的鎖System.out.println(this.girlName+"獲得口紅的鎖");Thread.sleep(1000);//放在這兒會造成死鎖/*synchronized (mirror){//一秒鐘后想獲得鏡子System.out.println(this.girlName+"獲得鏡子的鎖");}*/}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+"獲得的口紅的鎖");}*/}synchronized (lipstick){//兩秒中后想獲得口紅System.out.println(this.girlName+"獲得的口紅的鎖");}}}}白雪公主獲得鏡子的鎖
灰姑涼獲得口紅的鎖
白雪公主獲得的口紅的鎖
灰姑涼獲得鏡子的鎖
總結
- 上一篇: d0...while循环结构讲解
- 下一篇: C语言 goto 语句 - C语言零基础