哲學家問題除死鎖-java解法

哲學家問題,java去除死鎖的解法,琢磨了半天,要避免死鎖就必須在得不到右邊的筷子情況下放棄左邊的筷子,如此纔可!正所謂,退一步海闊天空。。。。

public class Zhexuejia {

public static void main(String[] args) throws Exception{
new Zhexuejia().t();
}
public void t() throws Exception{
Jia j1 = new Jia("哲學家1", x1, x2);
Jia j2 = new Jia("哲學家2", x2, x3);
Jia j3 = new Jia("哲學家3", x3, x4);
Jia j4 = new Jia("哲學家4", x4, x5);
Jia j5 = new Jia("哲學家5", x5, x1);
j1.start();
j2.start();
j3.start();
j4.start();
j5.start();
j1.join();
j2.join();
j3.join();
j4.join();
j5.join();
}
class Kuaizi{
String name;
public Kuaizi(String name){
this.name = name;
}
boolean enable = true;
public boolean pickup(Kuaizi r){
synchronized (this) {
int c = 0;
while(!enable&&c<3){
try {
c++;
this.wait(50);//先放出去自己讓別人用
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(!enable){//嘗試3次努力還是沒有得到就放棄前面的r
if(r != null)
r.down();
return false;
}
enable = false;
return true;
}
}
public void down(){
synchronized (this) {
enable = true;
notifyAll();
}
}
public String toString(){
return name;
}
}
private Kuaizi x1 = new Kuaizi("x1");
private Kuaizi x2 = new Kuaizi("x2");
private Kuaizi x3 = new Kuaizi("x3");
private Kuaizi x4 = new Kuaizi("x4");
private Kuaizi x5 = new Kuaizi("x5");

class Jia extends Thread{
Kuaizi lX, rX;
String name;
public Jia(String name, Kuaizi lX, Kuaizi rX){
this.name = name;
this.lX = lX;
this.rX = rX;
}
public void run(){
int c = 100;
boolean rs;
while(c-- > 0){
try {
System.out.println(name + " 想吃飯");
rs = lX.pickup(null);
// synchronized (lX) {//先得到座標的筷子
if(rs){
System.out.println(name + " 獲得了 " + lX + "筷子,等待右邊的...");
}else{
System.out.println(name + " 得不到"+lX+",悲催啊");
continue;
}
rs = rX.pickup(lX);
// synchronized (rX) {//再得到右邊的筷子,如果得不到也不放棄左邊的,容易死鎖,想避免就必須在得不到的情況下放棄左邊的筷子
if(rs){
System.out.println(name + " 終於獲得了 " + rX
+ "筷子,開始吃飯...");
}else{
System.out.println(name + " 得不到"+rX+",放棄"+lX+",悲哀啊");
continue;
}
// }

System.out.println(name + " 放棄 " + rX + "筷子");
rX.down();
// }
System.out.println(name + " 放棄 " + lX + "筷子");
lX.down();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
發佈了21 篇原創文章 · 獲贊 0 · 訪問量 3529
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章