我已经使用 Java 中的 Monitor (Synchronized) 实现了餐饮哲学家问题。
该计划的目标是:
每个哲学家都应该遵循思考、拿筷子、吃饭、放筷子的工作流程(没有比赛条件)。
无死锁
我认为这段代码似乎工作正常,但有些地方不对,因为它永远运行我试图调试它,调试工具停在这一行哲学家[i].t.join(); 但该程序并未终止。
请帮助我确定问题或告诉我如何解决它。感谢您的意见。
MyMonitor 类:
class MyMonitor {
private enum States {THINKING, HUNGRY, EATING};
private States[] state;
public MyMonitor() {
state = new States[5];
for(int i = 0; i < 5; i++) {
state[i] = States.THINKING;
System.out.println("Philosopher " + i + " is THINKING");
}
}
private void test(int i) {
if((state[(i+4)%5]!=States.EATING) && (state[i]==States.HUNGRY) && (state[(i+1)%5]!=States.EATING)) {
state[i] = States.EATING;
System.out.println("Philosopher " + i + " is EATING");
notify();
}
}
public synchronized void pickup(int i) {
state[i] = States.HUNGRY;
System.out.println("Philosopher " + i + " is HUNGRY");
test(i);
if (state[i] != States.EATING) {
System.out.println("Philosopher " + i + " is WAITING");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void putdown(int i) {
state[i] = States.THINKING;
System.out.println("Philosopher " + i + " is THINKING");
test((i+4)%5);
test((i+1)%5);
}
}
我的哲学家类:
class MyPhilosopher implements Runnable{
private int myID;
private int eatNum;
private MyMonitor monitor;
private Thread t;
public MyPhilosopher(int myID, int eatNum, MyMonitor monitor) {
this.myID = myID;
this.eatNum = eatNum;
this.monitor = monitor;
t = new Thread(this);
t.start();
}
public void run() {
int count = 1;
while(count <= eatNum ){
monitor.pickup(myID);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
monitor.putdown(myID);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
public static void main(String[] args) {
int eatNum = 10;
System.out.println("----------------------------------------------------------------------------------------------------");
System.out.println("xxx");
System.out.println("xxx");
System.out.println("xxx");
System.out.println("----------------------------------------------------------------------------------------------------");
System.out.println("Starting");
System.out.println("----------------------------------------------------------------------------------------------------");
System.out.println("");
MyMonitor monitor = new MyMonitor();
MyPhilosopher[] philosopher = new MyPhilosopher[5];
for(int i = 0; i < 5; i++) {
philosopher[i] = new MyPhilosopher(i, eatNum, monitor);
}
for(int i = 0; i < 5; i++) {
try {
philosopher[i].t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("----------------------------------------------------------------------------------------------------");
System.out.println("Ended");
}
}