在 JLS 17.4.4 , 它说
Every execution has a synchronization order. A synchronization order is a total order over all of the synchronization actions of an execution.
我知道什么是全序。而且我知道需要对同步操作进行排序。但是这里让我感到困惑的是为什么它是ALL 同步操作的总顺序。例如,监视器 m 上的解锁操作发生在 m 上的所有后续锁定操作之前。但是如果同时,在监视器n上有锁定 Action ,是否需要在监视器m解锁 Action 之后命令?如果不是,那为什么所有的同步 Action 都能有一个总序呢?谢谢。
最佳答案
好问题。虽然我不确定答案,但我认为最符合我理解的解释是肯定的,两个不同的锁之间存在“同步顺序”,因为 JLS 17.4.2将描述为按“同步顺序”排序的操作定义为必须是线程间的(因此一个线程必须在另一个线程接收操作之前已分派(dispatch)该操作)。
但是,这里有一个问题:
Synchronization actions induce the synchronized-with relation on actions, defined as follows [...]
只有 synchronized-with 命令的操作才能产生所需/期望的内存效果(即提升缓存状态)。
所以基本上,尽管您所有的“同步操作”都遵循“同步顺序”(因此也是“总顺序”),但只有那些synchronized-with 模式才对线程安全有效。 p>
关于java - 如何理解同步顺序是一个总顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44565995/