IllegalMonitorStateException on wait() call

后端 未结 10 1448
感动是毒
感动是毒 2020-11-22 11:37

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.IllegalMonit

10条回答
  •  执念已碎
    2020-11-22 11:58

    Thread.wait() call make sense inside a code that synchronizes on Thread.class object. I don't think it's what you meant.
    You ask

    How can I make a thread wait until it will be notified?

    You can make only your current thread wait. Any other thread can be only gently asked to wait, if it agree.
    If you want to wait for some condition, you need a lock object - Thread.class object is a very bad choice - it is a singleton AFAIK so synchronizing on it (except for Thread static methods) is dangerous.
    Details for synchronization and waiting are already explained by Tom Hawtin. java.lang.IllegalMonitorStateException means you are trying to wait on object on which you are not synchronized - it's illegal to do so.

提交回复
热议问题