I am trying to use wait and notify to halt threads until a certain method is called. I currently have it setup as the following:
On thread has a method with:
public void toggleTurnOver(){
if(turnOver == false){
turnOver = true;
synchronized(this){
for(Player p: playerList){
p.notify();
}
}
}else{
turnOver = false;
}
}
This method will be what is waking up the other wait that is located in this thread:
synchronized(myGame){
if(!myGame.getTurnOver()){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pr.println(myGame.getTurnOver());
pr.flush();
}
}
They are synchronized on the same object so am not sure what would be causing that exception to be thrown. Any ideas?
Exact error thrown is:
Exception in thread "Thread-3" Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at Player.run(Player.java:112)
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at Game.toggleTurnOver(Game.java:764)
at Game.run(Game.java:386)