主题:[讨论]网站上已有程序求解java的哲学家就餐问题的有关死锁问题
程序如下
public class kuai {
String name;
boolean Enable = true;
public kuai(String name) {
this.name = name;
}
public synchronized void pickup(){
try {
while(Enable==false){
this.wait();
}
this.Enable =false;
}
catch (Exception e) {
}
}
public synchronized void putdown() {
this.Enable =true;
this.notifyAll();
}
public static void main(String args[]) {
kuai k1 = new kuai("筷子1号");
kuai k2 = new kuai("筷子2号");
kuai k3 = new kuai("筷子3号");
kuai k4 = new kuai("筷子4号");
kuai k5 = new kuai("筷子5号");
People p1 = new People("老大", k1, k2);
People p2 = new People("老二", k2, k3);
People p3 = new People("老三", k3, k4);
People p4 = new People("老四", k4, k5);
People p5 = new People("老幺", k5, k1);
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
}
}
class People extends Thread {
String name;
kuai left;
kuai right;
public People(String name, kuai l, kuai r) {
this.name = name;
left = l;
right = r;
}
public void run() {
left.pickup();
System.out.println(name + " 眼明手快,以迅雷不及掩耳之势一把抓起 "+left.name);
right.pickup();
System.out.println(name + " 眼明手快,以迅雷不及掩耳之势一把抓起 "+right.name);
System.out.println(name + " 左右开弓,狼吞虎咽起来");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
System.out.println(name + " 酒足饭饱,打了个饱嗝,心满意足的放下了 "+left.name+" 和 " +right.name);
left.putdown();
right.putdown();
}
}
网站上搜到的,结果不是5个都已经有吃完了吗,为什么有人说会有死锁发生呢,主要我们没学操作系统,不太理解这方面
如果可以想帮忙添加下如
写一程序防止死锁的发生,让每位哲学家都有吃的机会。并在屏幕上打印出有多少哲学家在思考,在工作,在吃。
http://zhidao.baidu.com/question/29725362.html
要可以的话,分可以到baidu那边加