面試-計算機網路
阿新 • • 發佈:2022-03-16
-
多個執行緒各自佔有一些共享資源,並且互相等待其他執行緒佔有的資源才能執行,而導致兩個或者多個執行緒都在等待對方釋放資源,都停止執行的情形。某一個同步塊同時擁有 ”兩個以上物件的鎖“ 時,就可能會發生 “死鎖” 的問題。
package com.thread.lock;
//死鎖:多個執行緒互相抱著對方需要的資源,然後形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup girl1 = new Makeup(0,"小紅");
Makeup girl2 = new Makeup(1,"小婷");
girl1.start();
girl2.start();
}
}
//口紅
class Lipstick{
}
//鏡子
class Mirror{
}
class Makeup extends Thread{
//資源各只有一份,用static來保證只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String girlName;
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
小紅獲得口紅 小婷獲得鏡子 (死鎖)
package com.thread.lock;
//死鎖:多個執行緒互相抱著對方需要的資源,然後形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup girl1 = new Makeup(0,"小紅");
Makeup girl2 = new Makeup(1,"小婷");
girl1.start();
girl2.start();
}
}
//口紅
class Lipstick{
}
//鏡子
class Mirror{
}
class Makeup extends Thread{
//資源各只有一份,用static來保證只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String girlName;
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
小紅獲得口紅 小婷獲得鏡子 小婷獲得口紅 小紅獲得鏡子 (死鎖解決)
產生死鎖的四個必要條件:
-
互斥條件:一個資源每次只能被一個程序使用。
-
請求與保持條件: 一個程序因請求資源而阻塞時,對已獲得的資源保持不放。
-
不剝奪條件:程序已獲得的資源,在末使用完之前,不能強行剝奪。
-
迴圈等待條件:若干程序之間形成一種頭尾相接的迴圈等待資源關係。