Java中的易失性变量 [英] Volatile variable in Java
问题描述
因此,我正在阅读这本名为 Java Concurrency in Practice 的书,我坚持这一个解释,我没有一个例子似乎不能理解。这是引号:
So I am reading this book titled Java Concurrency in Practice and I am stuck on this one explanation which I cannot seem to comprehend without an example. This is the quote:
当线程
A
写入volatile
变量,随后线程B
读取同一变量,
可见的所有变量的值
变量之前,可以看到< code> B >
When thread
A
writes to a volatile variable and subsequently threadB
reads that same variable, the values of all variables that were visible toA
prior to writing to the volatile variable become visible toB
after reading the volatile variable.
有人可以给我一个反例,为什么 A $ c $可见的ALL变量的值在读取易变量变量之前,向
B
变量可见的写入变量变量
Can someone give me a counterexample of why "the values of ALL variables that were visible to A
prior to writing to the volatile variable become visible to B
AFTER reading the volatile variable"?
困惑为什么所有其他非易失性变量在读取volatile变量之前不会变为可见 B
?
I am confused why all other non-volatile variables do not become visible to B
before reading the volatile variable?
推荐答案
线程B可以有这些变量的CPU本地缓存。读取volatile变量可确保任何中间高速缓存从以前写入volatile到flush。
Thread B may have a CPU-local cache of those variables. A read of a volatile variable ensures that any intermediate cache flush from a previous write to the volatile is observed.
有关示例,请阅读以下链接,使用Volatile修复双重检查锁定:
For an example, read the following link, which concludes with "Fixing Double-Checked Locking using Volatile":
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
这篇关于Java中的易失性变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!