Java文档中的易失性变量说明 [英] Volatile variable explanation in Java docs

查看:147
本文介绍了Java文档中的易失性变量说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


当线程读取volatile变量时,它不仅会看到volatile的最新更改,还会看到导致更改的代码的副作用

when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change

http:/ /docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

有人可以举一个例子吗?

Can someone please provide an example of this?

这首先给我的印象是,读取volatile变量的线程将与writer线程同步并等待写入完成。但事实显然并非如此。

This first gave me an impression that the thread that reads a volatile variable will synchronize with the writer thread and wait until the write is done. But that clearly is not the case.

一个例子会有很多帮助并且非常感激。

An example would help a lot and be much appreciated.

谢谢,
Mustafa

Thanks, Mustafa

推荐答案

假设您有以下课程:

public class Shared {
    public int a;
    public int b;
    public volatile int c;
}

现在让我们假设线程A引用了这个类的实例,

Now let's say that thread A has a reference to an instance of this class and does

shared.a = 1;
shared.b = 2;
shared.c = 3;

让我们说线程B有对同一个实例的引用并且

And let's say that thread B has a reference to the same instance and does

display(c);
display(b);
display(a);

然后,如果c显示的值是3(即如果之前发生了线程A的写入)读取线程B),然后由Java内存模型保证2和1也将分别显示为b和a,因为在写入volatile c之前所做的所有线程A的操作都是有保证的被读取c的新值的线程可见。

Then, if the value displayed for c is 3 (i.e. if the write of thread A has happened before the read of thread B), then it's guaranteed by the Java memory model that 2 and 1 will also be displayed for b and a respectively, because all the actions of thread A that have been made prior to the write to the volatile c are guaranteed to be visible by a thread that has read the new value of c.

这篇关于Java文档中的易失性变量说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆