有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java易失性写入与非易失性写入重新排序

是否使用非易失性写入对易失性写入进行重新排序
例如:
我有两个线程T1和T2:

T1:

i = 10;  
volatile boolean result = true;

T2:

while(!result){
}

System.out.println(i);

T2总是看到i(10)的更新值还是旧值


共 (2) 个答案

  1. # 1 楼答案

    对。volatile语句有一个before关系:

    请考虑此堆栈溢出问题:Does Java volatile variables impose a happens-before relationship before it is read?

    A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.

    您还可以阅读《Java并发实践》一书中的第3.1.3节(锁定和可视性)。这里有一个关于类似可见性问题的相关解释,概述如下:

    Locking is not just about mutual exclusion; it is also about memory visibility.To ensure that all threads see the most up to date values of shared mutable variables, the reading and writing threads must synchronize on a common lock

    在代码中,锁是可变变量

  2. # 2 楼答案

    据我所知,这是正确同步的,所以没有比赛发生,10总是打印出来

    重要的部分是,在线程中,事情按程序顺序发生,对易失性变量的写入发生在看到该值的读取之前。与传递闭包规则一起,这意味着对i的赋值发生在print语句之前

    i = 10发生在result = true之前result = true发生在线程2中result被读取为true之前result被读取为在System.out.println(i);之前发生的true。因此,i = 10发生在System.out.println(i);之前