Why Lock condition await must hold the lock

后端 未结 6 1199
梦毁少年i
梦毁少年i 2020-12-29 05:29

I am in doubt with that , in Java language, we need to acquire the lock, before we await some condition to be satisfied.

For example, int java monitor lock:

6条回答
  •  太阳男子
    2020-12-29 06:11

    See the doc for Condition.

    A Condition is like a wait pool or wait set of an object and it replaces the use of the Object monitor methods (wait, notify and notifyAll). Conditions enable one thread to suspend execution (to "wait") until notified by another thread that some state condition may now be true. A Condition instance is intrinsically bound to a lock just like the Object monitor methods require the lock of the shared object to wait or notify on. So before invoking await() on a condition, the thread must have locked the Lock object that is used to produce the condition. When the await() method is invoked, the lock associated with the condition is released.

提交回复
热议问题