java - volatile 变量和发生在订购前

标签 java volatile

<分区>

我有两个线程:

线程: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 变量的读取都不会“错过”写入。

关于java - volatile 变量和发生在订购前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3971095/

相关文章:

java - 如何理解JDK9的内存模型?

c - 易变的变量

java - 我似乎无法从一组中获取所有数据?

Java流迭代列表最有效的方法

java - 使用自定义 ClassPathResource 配置 Spring 4 PropertySourcesPlaceholderConfigurer

python - 获取文件保存的目录(tkinter filesave 提示)

java - 没有选择的 SWT 表

java - 在java中从一个时区转换为另一个时区

.net - 我们能保证通过数据竞争缓存哈希码能正常工作吗?