gpt4 book ai didi

java - 为什么必须从同步块(synchronized block)/方法调用等待和通知?

转载 作者:行者123 更新时间:2023-11-30 11:24:40 25 4
gpt4 key购买 nike

<分区>

我正在读的书里说:

This technique is needed due to a race condition that would otherwise exist between setting and sending the notification and testing and getting the notification. If the wait() and notify() mechanism were not invoked while holding the synchronization lock, there would be no way to guarantee that the notification would be received.

不明白这到底是什么意思,为什么会出现race condition?

编辑:嗯,我现在知道这可能是 Why must wait() always be in synchronized block 的重复问题,但答案集中在进行条件检查和等待同步上。

来自 shrini1000 的反例:

I can still do something like:
while(!condition) { synchronized(this) { wait(); } }
which means there's still a race between checking the condition and waiting even if wait() is correctly called in a synchronized block. So is there any other reason behind this restriction, perhaps due to the way it's implemented in Java?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com