我正在阅读一篇关于 Java Volatile 关键字的文章,遇到了一些问题。 click here
public class MyClass {
private int years;
private int months
private volatile int days;
public void update(int years, int months, int days){
this.years = years;
this.months = months;
this.days = days;
}
}
udpate()方法写入了三个变量,其中只有days是volatile的。
完整的 volatile 可见性保证意味着,当一个值被写入 days 时,线程可见的所有变量也被写入主内存。这意味着,当一个值写入天时,年和月的值也会写入主存。
那么,“线程可见的所有变量”是什么意思呢? 是指线程栈中的所有变量吗? “对线程可见”是什么意思?我怎么知道月份和年份对线程可见?
最佳答案
都是关于happens-before
relationship的.
This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement.
在同一个线程中,
this.years = years; this.months = months;
happens-before
:this.days = days;
- 在不同线程中,volatile变量的写入
happens-before
阅读器线程读取volatile 变量。
而且,happens-before
关系有 transitivity .当读取线程看到volatile变量days
的新鲜值时,它也可以读取years
和months
的新鲜值。
关于java - 完全 volatile 可见性保证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57569133/