Java面试基础问题之(二十一)—— 线程持有的任何对象.wait()都会使线程陷入阻塞吗

直接上代码:

结果:

抛出了一个异常: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()才能使线程(本线程)陷入阻塞,或者唤醒其他线程(同步代码块执行完毕后)。

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值