关于volatile防止重排序
来源:13-5 volatile作用

qq_邪饿的小强_0
2019-12-04
关于volatile关键字防止重排序,在之前重排序的例子中,也就是OutOfOrderExecution这个类,如果我只对x,y两个变量加上volatile修饰的话,应该也可以达到代码不会出现x = 0;y = 0;的情况。因为 a = 1;一定发生在x = b之前;b = 1;一定发生在y = a;之前。不知道我的理解哪里出了问题,希望老师指正…
2回答
-
麻烦同学贴一下完整代码
022019-12-05 -
qq_邪饿的小强_0
提问者
2019-12-05
public class OutOfOrderExecution {
private static volatile int x = 0;
private static volatile int y = 0;
private static int a = 0, b = 0;
public static void main(String[] args) throws InterruptedException {
int i = 0;
while (true) {
i++;
x = y = a = b = 0;
final CountDownLatch countDownLatch = new CountDownLatch(1);
Thread one = new Thread(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
a = 1;
x = b;
});
Thread two = new Thread(() -> {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
b = 1;
y = a;
});
one.start();
two.start();
countDownLatch.countDown();
one.join();
two.join();
String result = "第" + i + "次(" + "x = " + x + " y = " + y + ")";
//只有重排序的时候回出现x y 都等于0
if(x == 0 && y == 0){
System.out.println(result);
break;
}
//1. 1,0 2.0,1 3.1,1
System.out.println(result);
}
}
}022019-12-05
相似问题