我想模擬一個母親通話三個子吃晚飯,這裏是我的代碼:的Java notifyAll的:拋出:IllegalMonitorStateException
class child extends Thread{
String name;
mother mom;
public child(mother mon, String name){
this.name = name;
this.mom = mom;
}
public void run(){
System.out.println(name+" is hungry.");
while (!mom.finished){
try {
wait();
}catch(InterruptedException e){}
}
washhands();
}
public synchronized void washhands(){
System.out.println(name+" washed hands.");
notifyAll();
}
}
class mother{
boolean finished;
public mother(){
finished = false;
}
public void cook(){
System.out.println("Mom started cooking.");
try{
Thread.sleep(200);
}catch(InterruptedException e){};
finished = true;
System.out.println("Mom finished cooking.");
notifyAll();
}
}
public class work{
public static void main(String[] args){
mother mom = new mother();
child Alex = new child(mom, "Alex");
child James = new child(mom, "James");
child Tod = new child(mom, "Tod");
Alex.start();
James.start();
Tod.start();
mom.cook();
}
}
所以我「在線程異常‘主’java.lang.IllegalMonitorStateException」得到了在類的母親notifyAll()的行。我不知道會發生什麼,有人能幫助我嗎?
wait和notify只能在有人看守的塊被調用,看看這個鏈接https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth .html – 11thdimension
您是否需要直接使用wait和notifyAll?如果不是,我建議'java.util.concurrent.Semaphore「。 –
你需要在Mom類中捕獲子對象,然後通知他們 –