我需要一些帮助。我正在尝试创建一个示例,说明需要使用易失性来防止指令重新排序。
在这个例子中,我试图证明,只有当重新排序发生时,b>a才会发生,并且易失性会阻止它。
问题是,在每次运行中,我都会得到b>a,我一定是错过了一些愚蠢的东西,但我看不见它。
我在这里错过了什么?
public class Example04Reorder extends Thread {
volatile static int a = 0;
volatile static int b = 0;
public static void main(String[] args) throws InterruptedException {
Example04Reorder t = new Example04Reorder();
t.start();
while( true )
{
if ( b > a ) // supposedly happens only on reordering
{
System.out.println("b was bigger than a");
System.exit(1);
}
}
}
public void run() {
while (true)
{
a = 5;
b = 4;
b = 0;
a = 0;
}
}
}发布于 2018-10-04 13:13:29
这里没有问题。比较操作符中有两个读操作。而且,由于在第二个线程中的赋值之间没有延迟,所以它们被暂时执行。因此,有可能第一个线程为b获得值4,而在读取值为a时,该值已经设置为0。所以这就是你得到结果的原因。
https://stackoverflow.com/questions/52647427
复制相似问题