简体   繁体   中英

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.

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? 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覆盖了:通过同步方法写入对象的任何字段发生在随后通过同步方法读取同一对象的任何其他字段之前

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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