gpt4 book ai didi

java - 无法理解 Java 规范中的 volatile 示例

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:54 26 4
gpt4 key购买 nike

我大致了解了 volatile 在 Java 中的含义。但读书 Java SE Specification 8.3.1.4我无法理解该特定示例下方的文字。

class Test {
static volatile int i = 0, j = 0;
static void one() { i++; j++; }
static void two() {
System.out.println("i=" + i + " j=" + j);
}
}

This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread. Therefore, the shared value for j is never greater than that for i, because each update to i must be reflected in the shared value for i before the update to j occurs. It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i, because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j.

怎么样

j never greater than i

,但同时

any given invocation of method two might observe a value for j that is much greater than the value observed for i

??

看起来很矛盾。

运行示例程序后,我得到的j 大于i。为什么要使用 volatile 呢?它在没有 volatile 的情况下给出几乎相同的结果(而且 i 可以大于 j,规范中的先前示例之一)。为什么这个示例在这里作为 synchronized 的替代方法?

最佳答案

在任何时候,j 都不大于i

这与方法二观察到的不同,因为它在不同的时间访问变量 iji 先被访问,j 稍微晚一点被访问。

这不是同步版本的直接替代方案,因为行为不同。与不使用 volatile 的一个区别是,如果不使用 volatile,则始终可以打印 0 值。增量永远不需要可见。

该示例演示了可变访问的顺序。一个需要这个的例子可能是这样的:

volatile boolean flag = false;
volatile int value;

// Thread 1
if(!flag) {
value = ...;
flag = true;
}

// Thread 2
if(flag) {
System.out.println(value);
flag = false;
}

线程 2 读取线程 1 设置的值而不是旧值。

关于java - 无法理解 Java 规范中的 volatile 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41026442/

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