Search code examples
javamultithreadingwait

IllegalMonitorStateException on wait() call


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?


Solution

  • You need to be in a synchronized block of the object you want to wait on 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.

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