IllegalMonitorStateException on wait() call

后端 未结 10 1449
感动是毒
感动是毒 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 12:06

    In order to deal with the IllegalMonitorStateException, you must verify that all invocations of the wait, notify and notifyAll methods are taking place only when the calling thread owns the appropriate monitor. The most simple solution is to enclose these calls inside synchronized blocks. The synchronization object that shall be invoked in the synchronized statement is the one whose monitor must be acquired.

    Here is the simple example for to understand the concept of monitor

    public class SimpleMonitorState {
    
        public static void main(String args[]) throws InterruptedException {
    
            SimpleMonitorState t = new SimpleMonitorState();
            SimpleRunnable m = new SimpleRunnable(t);
            Thread t1 = new Thread(m);
            t1.start();
            t.call();
    
        }
    
        public void call() throws InterruptedException {
            synchronized (this) {
                wait();
                System.out.println("Single by Threads ");
            }
        }
    
    }
    
    class SimpleRunnable implements Runnable {
    
        SimpleMonitorState t;
    
        SimpleRunnable(SimpleMonitorState t) {
            this.t = t;
        }
    
        @Override
        public void run() {
    
            try {
                // Sleep
                Thread.sleep(10000);
                synchronized (this.t) {
                    this.t.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题