題目描述
Java代碼模擬死鎖
死鎖條件
- 互斥使用:一個資源只能分配給一個線程
- 不可剝奪:資源只能由占有者釋放锰扶,申請者不能強(qiáng)制剝奪
- 請求保持:線程申請資源時衫贬,保持對原有資源的占有
- 循環(huán)等待:存在一個進(jìn)程等待隊(duì)列:{P1 , P2 , … , Pn}, 其中P1等待P2占有的資源讹堤,P2等待P3占有的資源祭刚,…辛孵,Pn等待P1占有的資源丛肮,形成一個進(jìn)程等待環(huán)路
代碼
思路
- 定義兩個資源o1,o2
- 對象deadLock1占有資源o1魄缚,需要資源o2
- 對象deadLock2占有資源o2宝与,需要資源o1
- 死鎖產(chǎn)生
代碼
public class DeadLock implements Runnable {
// flag=1,占有對象o1冶匹,等待對象o2
// flag=0习劫,占有對象o2,等待對象o1
public int flag = 1;
// 定義兩個Object對象嚼隘,模擬兩個線程占有的資源
public static Object o1 = new Object();
public static Object o2 = new Object();
public static void main(String[] args) {
DeadLock deadLock1 = new DeadLock();
DeadLock deadLock2 = new DeadLock();
deadLock1.flag = 0;
deadLock2.flag = 1;
Thread thread1 = new Thread(deadLock1);
Thread thread2 = new Thread(deadLock2);
thread1.start();
thread2.start();
}
public void run() {
System.out.println("flag: " + flag);
// deadLock2占用資源o1诽里,準(zhǔn)備獲取資源o2
if (flag == 1) {
synchronized (o1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("1");
}
}
}
// deadLock1占用資源o2,準(zhǔn)備獲取資源o1
else if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("0");
}
}
}
}
}