直接上代码:
结果:
抛出了一个异常:IllegalMonitorStateException
去官方文档查看IllegalMonitorStateException类(是个Exception的子类)的信息:
PS:链接:Class IllegalMonitorStateException
类说明:Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor
翻译过来即:一个线程在没有“拥有”某对象监视器的情况下,等待(wait)该对象的监视器,或者使用该监视器唤醒(notify)其他等待该监视器的线程。
有点绕口,对应到代码中,即没有拥有某对象监视器的情况下,调用了该对象的wait()和notity()或notifyall()。
显然,既然涉及到对象的监视器(monitor),则讨论的范畴必然在该对象作为“锁资源”的前提下,具体如何“owning the specified monitor”,其实有官方说明,这里不在贴官方网址,上其他博客参考资料:
A thread becomes the owner of the object's monitor in one of three ways:
1. By executing a synchronized instance method of that object.
2. By executing the body of a synchronized statement that synchronizes on the object.
3. For objects of type Class, by executing a synchronized static method of that class.
原文链接:诡异的java.lang.IllegalMonitorStateException
对应到传统的sychronized方法,即三种锁方式:
1. 执行实例sychronized方法,获得该实例的minitor
2. 执行sychronized(对象) {同步代码块}的同步代码块,获得该对象的minitor
3. 执行类sychronized方法,获得该类的minitor
那么关于标题的答案很明显了:
线程持有的任何对象.wait()都会使线程陷入阻塞吗?
答案:No,只有作为“锁”的对象,线程在内部调用其wait(),notity()或notifyall()才能使线程(本线程)陷入阻塞,或者唤醒其他线程(同步代码块执行完毕后)。