编辑 上面代码中的IllegalMonitorException背后的原因 在Java中,使用synced关键字是一种创建和获取监视对象的方法,该监视对象将用作锁来执行相应的代码块.在上面的代码中,监视程序为"Object.class".并且wait()方法告诉当前线程等待,直到通知它为止,并且您必须在拥有锁的监视对象上调用wait().因此调用wait()方法的方式如下所示,否则您将获得IllegalMonitorException. synchronized(monitor){monitor.wait();} 因此对于您的示例,您可以使用"Object.class.wait()" 或将监视器更改为 this ,因为您正在调用 wait()当前实例上的方法I do not understand why Java throw exception from subject in this code. Could somebody explain me it?class Wait implements Runnable{ public void run() { synchronized (Object.class) { try { while(true) { System.out.println("Before wait()"); wait(); System.out.println("After wait()"); } } catch (InterruptedException e) { e.printStackTrace(); } } }}public class ObjectMethodInConcurency{ public static void main(String[] args) { Wait w = new Wait(); (new Thread(w)).start(); }} 解决方案 Use synchronized (this) { instead of synchronized (Object.class) in your classEDITReasoning behind the IllegalMonitorException in above codeIn Java using synchronized keyword is a way to create and obtain a monitor object which will be used as lock to execute corresponding code block.In the above code that monitor is "Object.class".And wait() method tells the current thread to wait until it is notifyed and you have to invoke wait() on the monitor object which owns the lock.So the way to invoke wait() method is like below otherwise you will get IllegalMonitorException. synchronized(monitor){ monitor.wait();}So for your example you can either use "Object.class.wait()" or change the monitor to this since you are calling wait() method on the current instance 这篇关于当我以静态方式同步块调用wait()时,为什么Java抛出java.lang.IllegalMonitorStateException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-29 19:08
查看更多