volatile关键字有什么用? [英] What is the volatile keyword useful for?

查看:90
本文介绍了volatile关键字有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在工作中,我遇到了Java中的volatile关键字.不太熟悉它,我发现了此说明.

At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.

鉴于该文章详细解释了所涉及的关键字,您曾经使用过该关键字,还是曾经见过可以正确使用此关键字的情况?

Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?

推荐答案

volatile具有内存可见性的语义.基本上,volatile字段的值在所有读取器(尤其是其他线程)上完成写操作后变为可见.没有volatile,读者可能会看到一些未更新的值.

volatile has semantics for memory visibility. Basically, the value of a volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without volatile, readers could see some non-updated value.

要回答您的问题:是的,我使用volatile变量来控制某些代码是否继续循环.循环测试volatile值,如果它是true,则继续.可以通过调用停止"方法将条件设置为false.循环看到false并在stop方法完成执行后测试该值时终止.

To answer your question: Yes, I use a volatile variable to control whether some code continues a loop. The loop tests the volatile value and continues if it is true. The condition can be set to false by calling a "stop" method. The loop sees false and terminates when it tests the value after the stop method completes execution.

我强烈推荐的书" Java并发实践很好地解释了volatile.这本书是由撰写该问题中引用的IBM文章的同一人撰写的(实际上,他在该书的底部引用了他的书).我对volatile的使用被他的文章称为模式1状态标志".

The book "Java Concurrency in Practice," which I highly recommend, gives a good explanation of volatile. This book is written by the same person who wrote the IBM article that is referenced in the question (in fact, he cites his book at the bottom of that article). My use of volatile is what his article calls the "pattern 1 status flag."

如果您想进一步了解 Java内存模型.如果您想超越该级别,请阅读一本优秀的计算机体系结构书籍,例如轩尼诗& Patterson 并了解有关缓存一致性和缓存一致性的信息.

If you want to learn more about how volatile works under the hood, read up on the Java memory model. If you want to go beyond that level, check out a good computer architecture book like Hennessy & Patterson and read about cache coherence and cache consistency.

这篇关于volatile关键字有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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