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

查看:43
本文介绍了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 并在停止方法完成执行后测试该值时终止.

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."

如果您想了解更多关于 volatile 在幕后工作,阅读 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天全站免登陆