Why must wait() always be in synchronized block

后端 未结 10 1335
傲寒
傲寒 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:10

    @Rollerball is right. The wait() is called, so that the thread can wait for some condition to occur when this wait() call happens, the thread is forced to give up its lock.
    To give up something, you need to own it first. Thread needs to own the lock first. Hence the need to call it inside a synchronized method/block.

    Yes, I do agree with all the above answers regarding the potential damages/inconsistencies if you did not check the condition within synchronized method/block. However as @shrini1000 has pointed out, just calling wait() within synchronized block will not avert this inconsistency from happening.

    Here is a nice read..

提交回复
热议问题