我正在编写一个小的 Java 程序,我需要在其中创建线程(我的代码中的哲学家),而这些哲学家需要在思考、饥饿和进食之间改变状态。我对这个项目并没有那么远,我遇到了下一个问题:
public class NewMain {
static Philosopher [] p;
public static void main(String[] args) {
p = new Philosopher[5];
p[0] = new Philosopher(0);
p[1] = new Philosopher(1);
p[2] = new Philosopher(2);
p[3] = new Philosopher(3);
p[4] = new Philosopher(4);
for (int i = 0; i<5; i++) {
try{
p[i].run();
if(i == 4) {
p.notifyAll();
}
}
catch(IllegalMonitorStateException e) {}
}
}
}
我正在创建 5 个哲学家(线程)。每个人的wait()
代码中都有一条指令:
@Override
public void run() {
int rand;
if (status == 0) {
System.out.println("Philosopher " + id + " is waiting.");
try {
wait();
System.out.println("Awoken");
while(status == 0) {
System.out.println("Philosopher " + id + " is thinking.");
sleep(100);
rand = ThreadLocalRandom.current().nextInt(0,100);
if(rand > 95){
status = 1;
System.out.println("Philosopher " + id + " changed state to hungry.");
}
}
}
catch(InterruptedException e) {
System.out.println("Error!");
}
catch(IllegalMonitorStateException e) {}
}
}
问题是在调用时,进程并没有醒来,它们在执行每个线程notifyAll()
的方法后就死掉了。run()
如果有人想知道,我没有使用synchronized
,因为我需要同时运行这些方法。
另外,我试图把线程notifyAll()
的方法放在里面。run()
谁能告诉我发生了什么以及为什么线程没有继续他们的代码?