我有两个线程:
线程:1
a = 1;
x = b;
线程:2
b = 1
y = a
这里 a 和 b 被声明为 volatile。我不明白如何在 a = 1; 之间创建“先于发生”的边; y = 一个;在 x = b 之间; b = 1;
我知道通过使用 volatile 变量可以防止从线程缓存中读取陈旧的值。但是 volatile 变量如何确保 happens-before ordering。
具体来说,我不明白这一点:
a write to a volatile field happens
before every subsequent read of the
same field.
这行吗?
a write to a volatile field happens before every subsequent read of the same field.
这里重要的词是“后续”。
这是 Java 语言规范的相关部分 17.4.4 Synchronization Order :
Every execution has a synchronization order. A synchronization order is a total order over all of the synchronization actions of an execution. For each thread t, the synchronization order of the synchronization actions (§17.4.2) in t is consistent with the program order (§17.4.3) of t.
Synchronization actions induce the synchronized-with relation on actions, defined as follows:
- [...]
- A write to a volatile variable (§8.3.1.4) v synchronizes-with all subsequent reads of v by any thread (where subsequent is defined according to the synchronization order).
注意最后一部分。所以这就是说,如果您考虑程序操作的任何总排序,那么在该总排序中晚于写入的任何 volatile 变量的读取都不会“错过”写入。