你在Java中使用volatile关键字吗? [英] Do you ever use the volatile keyword in Java?

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

问题描述

今天上班时,我在Java中遇到了 volatile 关键字。我不太熟悉它,我找到了这样的解释:

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


Java理论与实践:管理波动性

鉴于该文章解释了相关关键字的详细信息,您是否曾使用它,或者您是否曾经看到过可以正确使用此关键字的情况?

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 。通过调用stop方法,可以将条件设​​置为 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.

本书< a href =http://jcip.net =noreferrer> Java Concurrency in Practice ,我强烈推荐,给出了 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.

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

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