IllegalMonitorStateException on wait() call

prakash.panjwani picture prakash.panjwani · Oct 8, 2009 · Viewed 262k times · Source

I am using multi-threading in java for my program. I have run thread successfully but when I am using Thread.wait(), it is throwing java.lang.IllegalMonitorStateException. How can I make a thread wait until it will be notified?

Answer

reccles picture reccles · Oct 8, 2009

You need to be in a synchronized block in order for Object.wait() to work.

Also, I recommend looking at the concurrency packages instead of the old school threading packages. They are safer and way easier to work with.

Happy coding.

EDIT

I assumed you meant Object.wait() as your exception is what happens when you try to gain access without holding the objects lock.