是否保证代码会跳出while循环?
不,Java 内存模型是根据“发生在”关系定义的:
两个动作可以通过happens-before关系排序。如果一个动作发生在另一个动作之前,那么第一个动作对第二个动作可见并在第二个动作之前排序。
规范继续说:
如果动作 x 与后续动作 y 同步,那么我们也有 hb(x, y)。
wherehb代表发生在之前,和
监视器 m 上的解锁操作与 m 上的所有后续锁定操作同步(其中“后续”根据同步顺序定义)。
另请注意:
如果 hb(x, y) 和 hb(y, z),则 hb(x, z)。
因此,在您的示例中,synchronized(lock)aroundb将为以下读取建立发生前的关系,因此b保证 的值在也使用的其他线程中可见synchronized(lock)。明确地说,
hb(write to b in threadOne, unlock in threadOne) AND
hb(unlock in threadOne, lock in threadTwo) AND
hb(lock in threadTwo, read from a in threadTwo) IMPLIES
hb(write to b in threadOne, read from b in threadTwo)
同样,a将保证对其他线程可见。明确地说,
hb(write to a in threadOne, lock in threadOne) AND
hb(lock in threadOne, unlock in threadOne) AND
hb(unlock in threadOne, lock in threadTwo) AND
hb(lock in threadTwo, read a in threadTwo) IMPLIES
hb(write to a in threadOne, read a in threadTwo).
写入和随后的读取c没有发生之前的关系,因此,根据规范,写入c不一定对threadTwo.
如果我们从方程中删除变量 c 怎么办?我想知道是否只有 b 保证在 threadTwo 中可见,因为它在同步块内。
是的,见上文。