I have created a class that extends Thread. I am running this by invoking the start() method on this object. I would also like to pause in this thread. By using wait() code throws an IllegalMonitorStateException.
How do I get rid of this exception? Pasted the code with the stack trace.
As a side note, wait() is usually used as part of inter-thread communication. Some other thread has to be able to wake this thread up using notify. Does some other thread have access to a reference to this thread? Using the Thread instance itself as the Object to wait() on is usually frowned upon - both for the previous reason and because you are more likely to get spurious wakeup signals with it. I would suggest you create a new Object whose specific purpose is to be used for the wait() / notify() (java.util.concurrent.locks.Lock and the related Condition work as a great alternatives with more 'expressive' interfaces.)
I don't know if it is clear for you, but you just need to put "synchronized" into the method (or code blocks) to be the ownership of the monitor (by default it uses the "this" as the monitor object ). Like the following code:
The answer in stackoverflow might help you as well:
Luan Cestari wrote:I don't know if it is clear for you, but you just need to put "synchronized" into the method (or code blocks) to be the ownership of the monitor (by default it uses the "this" as the monitor object ).
Although you are right in that is how you get ownership of the lock, just putting synchronized does not really let wait() work, it just prevents the exception. That is why Tim and I pointed the OP to documentation on how to use the method, rather than just telling him how to avoid an exception.
I think you are right as Ahsan thanked. Sorry, I posted before seen that reply and I was thinking that the Ahsan had a different question in mind (as he state "How do I get rid of this exception?" in the first post)