gpt4 book ai didi

java - 同步方法退出时发生

转载 作者:行者123 更新时间:2023-11-30 02:48:59 27 4
gpt4 key购买 nike

神谕 lesson on concurrency状态:

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.

这似乎是正确的,因为“后续”意味着它发生在同步方法退出之后。对于非同步方法来说,这种说法似乎也适用。我错过了什么?

最佳答案

你忽略了“随后”与时间的流逝无关;它只与方法调用在同步顺序中出现的位置有关。这是线性化(按挂钟时间严格排序,不受Java内存模型保证)和顺序一致性(“与某些排序一致”,保证对于无数据竞争的程序)。 “发生在之前”这个短语也是具有欺骗性的,因为它也不意味着时间顺序。

对于非同步方法,根本没有顺序,因为它们的调用不会出现在同步顺序中。

正如您在评论中很好地总结的那样:

Every execution has some order on synchronization actions which may or may not be the same as the "actual" execution order. However, this synchronization order is consistent with program order of individual threads. Moreover, if exiting a synchronized method occurs earlier in the synchronization order than entering a synchronized method on the same object, then all reads in the entered method see writes in the exited method.

关于java - 同步方法退出时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39293102/

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