Why must wait() always be in synchronized block

后端 未结 10 1116
傲寒
傲寒 2020-11-22 06:18

We all know that in order to invoke Object.wait(), this call must be placed in synchronized block, otherwise an IllegalMonitorStateException is thrown. But what\'s t

10条回答
  •  旧巷少年郎
    2020-11-22 07:01

    as per docs:

    The current thread must own this object's monitor. The thread releases ownership of this monitor.

    wait() method simply means it releases the lock on the object. So the object will be locked only within the synchronized block/method. If thread is outside the sync block means it's not locked, if it's not locked then what would you release on the object?

提交回复
热议问题