Why Lock condition await must hold the lock

后端 未结 6 1168
梦毁少年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条回答
  •  -上瘾入骨i
    2020-12-29 06:24

    a sounds-reasonable answer

    It is a JVM thing. An Object x has:

    • an Entry Set: a queue for threads attempting to synchronized(x)

    • a Waiting Set: a queue for threads called x.wait()

    When you call x.wait(), JVM adds your current thread into Waiting Set; when you call x.notify()/x.notifyAll(), JVM removes one/all element from Waiting Set.

    Multiple threads may call x.wait()/x.notify()/x.notifyAll() to modify the Waiting Set. In order to ensure the Waiting Set thread safety, JVM accepts only one operation from one thread at one time.

提交回复
热议问题