哲学家问题除死锁-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();
}
}
}
}
}
    原文作者:java锁
    原文地址: https://blog.csdn.net/iteye_17517/article/details/82057711
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞