gpt4 book ai didi

Java volatile 关键字 - 为什么此代码终止

转载 作者:行者123 更新时间:2023-12-01 18:12:00 24 4
gpt4 key购买 nike

我正在使用Java中的 volatile 关键字,并且我有这段代码试图表明一个线程看不到另一个线程引入的更改,除非我们将数据声明为 volatile 。我期望下面的代码永远不会终止,因为我没有将共享数据声明为 volatile 。知道为什么这段代码实际上终止吗?

public class VolatileTest {

public static void main(String[] args) throws InterruptedException {
var holder = new Holder();
new Thread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) { }
for(int i = 0; i<100000; i++) {
holder.counter++;
}
}).start();
var t = new Thread(() -> {
while(holder.counter < 10000) {
System.out.println("Jestem w pętli");
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
t.join();
}

static class Holder {
int counter = 0;
}

}

最佳答案

Thread 1可能看不到 Thread 2 的变化如果您不使用volatile,请立即,但最终有一天,当 Thread 2 时,就会发生这种情况。清空 CPU 缓存到主内存。在您的示例中,如果您使用 volatilecounter字段,当您调用 holder.counter++ 时,写入线程将始终写入主内存。每次调用 holder.counter < 10000 时,读取线程都会从主内存中读取数据.

关于Java volatile 关键字 - 为什么此代码终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60453052/

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