【发布时间】:2018-07-16 20:57:55
【问题描述】:
我正在编写一个小的 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() 方法中。
谁能告诉我发生了什么以及为什么线程没有继续 用他们的代码?
【问题讨论】:
-
如果您想将
run()附加到实际的操作系统线程中,您必须调用Thread.start()而不是Thread.run()。 -
你为什么要调用run来启动一个线程? Run 将像方法一样执行,它不会启动您的线程。这里需要notifyAll是什么?
标签: java multithreading wait notify dining-philosopher