简体   繁体   English

易失关键字无用当使用同步时?

[英]Volatile Keyword is of no use When using synchronized?

I was trying to understand the use of volatile keyword in java. 我试图了解在Java中使用volatile关键字。 I understand it will write the data in main memory not in thread cache. 我知道它将数据写入主内存中而不是线程缓存中。

But is that really useful. 但这真的很有用。 I am using multi threading and 我正在使用多线程和

shouldn't I be using synchronized cause I don't want dirty reads to other threads. 我不应该使用同步的原因,因为我不想脏读其他线程。 so at what exact situation volatile can be useful and most important to use? 那么在什么情况下挥发物可能有用并且最重要?

Please give some example. 请举个例子。

synchronized is much more expensive than plain volatile . synchronized比普通volatile要贵得多。

volatile is useful when you just need to read/write single variable and don't care about atomicity of complex structures. 当您只需要读/写单个变量并且不关心复杂结构的原子性时, volatile很有用。

synchronized is useful when you need to perform complex operations, update several variables or set one variable when compared another one and ensure the atomicity of such operation. 当您需要执行复杂的操作,更新多个变量或在与另一个变量进行比较时设置一个变量并确保此类操作的原子性时,“ synchronized很有用。 Also it is used when doing higher level synchronization such as conditions, ie synchronized / wait / notify in java. 也做得更高水平同步诸如条件当它被使用,即synchronized / wait / notify中的java。 But for that Lock / Condition can be used too. 但为此,也可以使用“ Lock / Condition

For even better explanation about using volatile variables you can view the following link with JB Nizet's answer. 有关使用volatile变量的更好解释,可以查看以下链接以及JB Nizet的答案。 It compliments well the answer posted by Zbynek and further explains the relation between volatile, atomic variables & complexity. 它很好地赞扬了Zbynek的答案,并进一步说明了可变性,原子变量与复杂性之间的关系。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM