gpt4 book ai didi

java - volatile 示例(在 JLS8/8.3.1.4 volatile 字段中)不起作用?

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

http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.1.4

Java 语言规范 8/8.3.1.4 volatile 字段

volatile example

问题:

在 volatile 的示例中,我在方法 two() 中添加了同步关键字,以避免在方法 two() 期间执行 one() .

但我仍然注意到 j 大于 i:为什么?

注意:

我使用 Java HotSpot 1.8.0_112。

If you can not noticed j is larger than i, please set testVolatile()/num to a larger number.

我的演示:

public class VolatileDemo {

static volatile int i = 0, j = 0;

static void one() {
i++;
j++;
}

static synchronized void two() {
if (i != j)
System.out.println("i=" + i + " j=" + j);
}

static void testVolatile() {
int num = 5000;
for (int i = 0; i < num; i++) {
new Thread(new Runnable() {
public void run() {
one();
}
}).start();
}
for (int i = 0; i < num; i++) {
new Thread(new Runnable() {
public void run() {
two();
}
}).start();
}
}

public static void main(String[] args) {
testVolatile();
}
}

我的结果:

i=4996 j=4998

i=4998 j=5000

i=4998 j=5000

...

最佳答案

这是可能的,并且在您提到的链接中进行了描述。它位于该段落的末尾。

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.

因此,two() 方法按照代码中的确切顺序读取 i,然后读取 j。但是读取之间有多个 one() 方法调用,给出的结果为 (4998, 5000)

关于java - volatile 示例(在 JLS8/8.3.1.4 volatile 字段中)不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44504320/

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