題目大意:
- 哲學家問題咖祭,每一個都有自己的筷子,同時需要獲取別人的筷子吃飯:
- 1.獲得筷子蔫骂,吃飯1秒么翰,然后趕緊放下筷子,思考3秒辽旋。
- 2.否則思考浩嫌。
編碼實現(xiàn)
- 利用靜態(tài)數(shù)組統(tǒng)一保存筷子,每個人的id和其中一個筷子綁定补胚。沒有自己的筷子固该,就不吃飯棺克,哼(¬︿??¬☆)孕荠。
- synchroinized(class)祟昭,鎖定所有哲學家實例肛真,保證線程安全桶良。
package interview.philosopherquestion;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 哲學家問題啄糙,每一個都有自己的筷子定枷,同時需要獲取別人的筷子吃飯:
* 1.獲得筷子偶摔,吃飯1秒金闽,然后趕緊放下筷子纯露,思考3秒。
* 2.否則思考代芜。
*/
public class PhilosopherByMe extends Thread{
//定義五個筷子:1表示可以使用埠褪,可以取筷子eating,0表示不可以使用,正在eating。钞速。贷掖。
private final static int[] ticks = {1, 1, 1, 1, 1};
private final int id;//不可變,線程安全
private int otherId;//只會在同步塊中修改渴语,線程安全
/**
* 每一個哲學家對應一個筷子
* @param id
*/
PhilosopherByMe(int id){
this.id = id;
}
public void eating(){
//鎖住所有對象實例
synchronized (PhilosopherByMe.class){
if(ticks[id] == 1){
for(int i = 0; i < 5; ++i){
if(i != id){
//可以獲得另外的筷子苹威,eating!<菪住牙甫!
if (ticks[i] == 1){
otherId = i;
ticks[i] = 0;
ticks[id] = 0;
//拿到銬子后,吃飯一秒调违。保持占有筷子窟哺,不能被其他sb拿走
System.out.println("哲學家" + id + "正在拿著" + id + " 和 " + otherId +" 號筷子吃飯!<技纭脏答!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//吃完飯,溜了溜了亩鬼。
return;
}
}
}
}
}
}
public void thinking(){
synchronized (PhilosopherByMe.class){
//放下自己的筷子和其他人的筷子
if (ticks[id] == 0 && ticks[otherId] == 0){
ticks[id] = 1;
ticks[otherId] = 1;
}
}
//放下筷子后殖告,思考3秒
System.out.println("哲學家" + id + "正在思考");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
eating();
thinking();
}
}
public static void main(String[] args) {
//5個哲學家,5個筷子
ExecutorService executors = Executors.newFixedThreadPool(5);
for(int i = 0; i < 5; ++i){
executors.submit(new PhilosopherByMe(i));
}
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者