话不多说,先上代码:
private static int x = 0,y = 0,a = 0, b = 0;
public static void main(String[] args) throws InterruptedException {
int i = 0;
for (;;){
i++;
x = 0;y = 0;
a = 0; b = 0;
Thread one = new Thread(() -> {
a = 1;
x = b;
});
Thread two = new Thread(() -> {
b = 1;
y = a;
});
one.start();two.start();
one.join();two.join();
String result = "第" + i + "次 (" + x + "," + y + ")";
System.out.println(result);
if(x == 0 && y == 0){
break;
}
}
}
如果不考虑指令重排序,x和y的结果有以下几种可能:
1.严格按照线程1和线程2顺序执行,x = 0,y = 1或者x = 1,y = 0;
2.当线程one执行到a = 1时,线程two就去执行了b = 1,然后再接着往下执行,此时x = 1 ,y = 1
永远不会出现x = 0,y = 0的情况。
但执行上面的程序的时候,发现有可能会break掉,说明发生了指令重排序的情况。
volatile底层是如何实现指令重排序的呢?
是因为加了内存屏障。