- 機構級別:普通會員
- 信用等級:
資料認證
未通過身份證認證
未通過辦學許可認證
- 學校瀏覽人次:次
- 加盟時間:2017年03月10日
西安尚學堂:java線程死鎖模擬
1,關于死鎖的理解
死鎖,我們可以簡單的理解為是兩個線程同時使用同一資源,兩個線程又得不到相應的資源而造成永無相互等待的情況。
2,模擬死鎖
背景介紹:我們創建一個朋友類,當朋友向我們鞠躬的時候,我們也要向朋友鞠躬,這樣才算一個完整的動作。當兩人
同時鞠躬的時候,都在等待對方鞠躬。這時就造成了死鎖。
模擬程序:
package com.yxy.thread;
/**
* @author windows
* 死鎖模擬程序
*/
public class Deadlock {
/**
* @author windows
* 朋友實體類
*/
static class Friend {
//朋友名字
private final String name;
//朋友實體類型的構造方法
public Friend(String name) {
this.name = name;
}
//獲取名字
public String getName() {
return this.name;
}
//朋友向我鞠躬方法,(同步的)
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
//我回敬鞠躬方法,(同步的)
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
//死鎖模擬程序測試開始
//創建兩個友人alphonse,Gaston
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
//啟動兩位友人鞠躬的線程。
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
})。start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
})。start();
}
}