“易变”是什么用Java表示? [英] What does "volatile" mean in Java?

查看:181
本文介绍了“易变”是什么用Java表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在其中一个项目中使用 volatile 来维护不同线程访问的变量的相同副本。我的问题是,使用 volatile static 一起使用是否可以。编译器没有给出任何错误,但我不明白使用两者的原因。

We use volatile in one of our projects to maintain the same copy of variable accessed by different threads. My question is whether it is alright to use volatile with static. The compiler does not give any errors but I don't understand the reason of using both.

推荐答案

阅读内存模型不够规范,我建议你阅读 http:// jeremymanson。 blogspot.com/2008/11/what-volatile-means-in-java.html 。它由JMM的一位作者撰写,应该回答你的问题。根据之前发生的条款考虑记忆读写也很有帮助; JMM for Java 5以后将语义添加到 volatile

Short of reading the memory model specification, I recommend you read http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html. It's written by one of the JMM authors and should answer your question. Thinking of memory reads and writes in terms of the happens-before clause is also helpful; the JMM for Java 5 onwards adds happens-before semantics to volatile.

具体来说,当你读取一个volatile变量时从一个线程,所有写入到包括从其他线程写入该volatile变量的写入现在对该一个线程可见。如果您有时间,可以进一步讨论该主题的Google技术讲座: https:// code.google.com/edu/languages/#_java_memmodel

Specifically, when you read a volatile variable from one thread, all writes up to and including the write to that volatile variable from other threads are now visible to that one thread. If you have some time, there's a Google tech talk that further discusses the topic: https://code.google.com/edu/languages/#_java_memmodel.

而且,是的,您可以使用 static volatile 。他们做了不同的事情。

And, yes, you can use static with volatile. They do different things.

这篇关于“易变”是什么用Java表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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