Java calls wait() throws an exception: IllegalMonitorStateException

If the thread calling the wait() method does not acquire the monitor lock of the object in advance, the calling thread will throw an IllegalMonitorStateException when calling the wait() method.

  • Solution:
    1. Use the shared variable as a parameter when executing the synchronized code block.
    synchronized(共享变量){
       // doSomething
    }
    
    1. Call the shared variable method, and the method uses synchronized decoration.
    synchronized void method(int a, int b){
    	// doSomething
    }
    

Refer to Tencent Cloud

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/109913848