java问题115

来源:百度知道 编辑:UC知道 时间:2024/09/21 08:36:13
What happens when thread X executes a wait() method on object A, without owning
object A’s lock?
A. Compilation fails.
B. An exception is thrown.
C. The wait() method has no effect.
D. Thread X receives the lock immediately.
E. Object A moves the thread to the wait pool.
请问这道题为什么选择B呢?为什么不是E?谢谢!

请看帮助文档:wait() method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
if the current thread is not the owner of the object's monitor,
IllegalMonitorStateException will be thrown.

就是说必须拥有此对象的锁其标,才可以调用此方法

因为wait方法的执行必须要首先获得当前线程对对象的控制权,如果没有,则会出现异常,wait在Object中以native方式实现