加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java文档中的易失性变量说明

发布时间:2020-12-14 05:52:46 所属栏目:Java 来源:网络整理
导读: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提到 有人可

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提到

有人可以提供一个例子吗?

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

一个例子可以帮助很多,并非常感激.

谢谢,
穆斯塔法

解决方法

假设您有以下课程:
public class Shared {
    public int a;
    public int b;
    public volatile int c;
}

现在让我们说线程A有一个对这个类的实例的引用

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

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

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

然后,如果为c显示的值是3(即如果在读取线程B之前发生了线程A的写入),则Java内存模型保证2和1也将分别显示为b和a,因为在写入易失性c之前已经进行的线程A的所有动作都保证被读取c的新值的线程可见.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读