IllegalMonitorStateException on wait() call

后端 未结 10 1458
感动是毒
感动是毒 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:52

    wait is defined in Object, and not it Thread. The monitor on Thread is a little unpredictable.

    Although all Java objects have monitors, it is generally better to have a dedicated lock:

    private final Object lock = new Object();
    

    You can get slightly easier to read diagnostics, at a small memory cost (about 2K per process) by using a named class:

    private static final class Lock { }
    private final Object lock = new Lock();
    

    In order to wait or notify/notifyAll an object, you need to be holding the lock with the synchronized statement. Also, you will need a while loop to check for the wakeup condition (find a good text on threading to explain why).

    synchronized (lock) {
        while (!isWakeupNeeded()) {
            lock.wait();
        }
    }
    

    To notify:

    synchronized (lock) {
        makeWakeupNeeded();
        lock.notifyAll();
    }
    

    It is well worth getting to understand both Java language and java.util.concurrent.locks locks (and java.util.concurrent.atomic) when getting into multithreading. But use java.util.concurrent data structures whenever you can.

提交回复
热议问题