Sign in to follow this  
Halsafar

[java] Java Pause a thread

Recommended Posts

Okay I got this class which extends Thread. I create an instance of this class, call start(), over-ride run() and it works. The thread runs fine and the main thread is free to continue. Now I need to have this new thread pause itself and wait for a notify call. Everytime I call .wait() I get a runtime exception: java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:474) Now, obviously, I am trying to call .wait() in a thread which doesn't own the object (my guess). But I am calling .wait() from within the thread itself... I am confused. Anyone care to code up a quick sample which shows the use of .wait() and .notify()? Provide any tips? btw, I love the new gamedev look :)

Share this post


Link to post
Share on other sites
Use the API docs

Quote:

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

By executing a synchronized instance method of that object.
By executing the body of a synchronized statement that synchronizes on the object.
For objects of type Class, by executing a synchronized static method of that class.

Share this post


Link to post
Share on other sites
Quote:
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}

and more precisselly this code.
Obj could be this. Of course you should call notify only... It would spoil the fun of debugging, if I would write it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this