简体   繁体   English

为什么我们必须使用相同的 volatile 字段来建立使用 volatile 关键字的happens-before关系?

[英]Why we must use same volatile field to establish happens-before relationship using the volatile keyword?

The 'Volatile Rule' says that 'A write to a volatile field happens-before every subsequent read of that same field', I DO know that this means if we write to a volatile thread and read another volatile in another thread, then there are NO happens-before relationship between the two actions. “易失性规则”说“写入易失性字段发生在每次后续读取同一字段之前”,我知道这意味着如果我们写入易失性线程并在另一个线程中读取另一个易失性,那么有NO 发生在两个动作之间的关系之前。

My queustion is why we must use 'same field'?我的问题是为什么我们必须使用“相同字段”?

That is how it should work isn't?那是它应该如何工作不是吗? All we want is the data shared between threads should be consistent, so why should we have happens-before relationship between different variables?我们想要的只是线程之间共享的数据应该是一致的,那么为什么我们要在不同的变量之间有happens-before关系呢? It makes sense to have happens before relationship on same field because if we don't then it may lead to data race.在同一字段上的关系之前发生是有意义的,因为如果我们不这样做,则可能会导致数据竞争。 isn't?不是吗?

因为您要求的内容被synchronized覆盖了:通过同步方法写入对象的任何字段发生在随后通过同步方法读取同一对象的任何其他字段之前

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

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