gpt4 book ai didi

java - 没有同步或 volatile 的内存可见性

转载 作者:行者123 更新时间:2023-12-01 16:47:15 25 4
gpt4 key购买 nike

如果没有“同步”或“ volatile ”关键字,一个线程所做的更改将永远不会被另一个线程看到(或不确定),这样说是否正确?我在多核平台上多次运行以下程序,结果不同。有时程序永远不会终止,这是预期的场景。但有时它会打印“1”退出。
JDK:jdk1.8.0_73
操作系统:CentOS Linux 版本 7.1.1503

public class VolatileTest implements Runnable {
private int i = 0;

public void run() {
i++;
i++;
}

public int get() {
return i;
}

public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
VolatileTest volatileTest = new VolatileTest();
executorService.execute(volatileTest);
while (true) {
int i = volatileTest.get();
if (i % 2 != 0) { //
System.out.format("i: %s \n", i);
System.exit(0);
}
}
}
}

最佳答案

Is it correct to say without "synchronized" or "volatile" keyword, changes made by one thread will never be seen by another (or non-deterministic)?

正确的说法是,如果从写入事件到后续的读取事件没有发生之前关系,则未指定会发生什么。

更改可能是立即的,也可能是延迟的,或者可能永远不可见。

更重要的是,更改可能会以意想不到的顺序变得可见。

在您的示例中,i 变量可以有 3 个可能的值,并且 main 线程将看到哪个值是未指定且不可预测的。您观察到的行为并不意外。

关于java - 没有同步或 volatile 的内存可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48247611/

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