Reputation: 83
I was wondering why I can't directly write what's in my battle.resume()
method right into my frame.keyPressed()
method? If I do so I get a IllegalMonitorStateException, I've found out on the net that this exception is "Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor" so I assumed it has to be directly in the class you want to wait/notify on.
Since I feel like an example is better than 10 lines, so here's a simplified version of what I don't understand, I don't understand why what I linked work and what's between /**/
doesn't, and if it is gonna work all the time.
My Battle class:
public class Battle{
public void run(){
while(true){
System.out.println("START");
synchronized(this){
try{
wait();
}catch(InterruptedException e){}
}
System.out.println("END");
}
}
public void resume(){
synchronized(this){
notify();
}
}
}
My Frame class:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class Frame extends JFrame implements KeyListener{
private Battle battle;
public Frame(){
this.battle = new Battle();
setTitle("ControlerPanel");
setSize(200, 200);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
setVisible(true);
battle.run();
}
public Battle getBattle(){
return battle;
}
@Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_A){
battle.resume();
}
}
@Override
public void keyReleased(KeyEvent e){}
@Override
public void keyTyped(KeyEvent e){}
}
Upvotes: 1
Views: 19
Reputation: 34597
synchronized(battle){
battle.notify();
}
should work. I assume you tried doing synchronized(this) in your keyPressed method, and "this" there referred to the Frame class, not battle. You need to have lock on the object that you are calling notify() on.
Upvotes: 0