CPU指令重排实例代码:
public class VolatileSample2 {
static volatile int a = 0, b = 0;
static /*volatile*/ int x = 0, y = 0;
public static void main(String[] args) throws InterruptedException {
int i = 0;
for (; ; ) {
i++;
a = 0;
b = 0;
x = 0;
y = 0;
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
shortWait(40000);
a = 1;
y = b;
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
b = 1;
x = a;
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
String result = "第" + i + "次, (" + x + "," + y + ")";
if (x == 0 && y == 0) {
System.err.println(result);
break;
} else {
System.out.println(result);
}
}
}
// 一段延迟代码
private static void shortWait(long interval) {
long start = System.nanoTime();
long end;
do {
end = System.nanoTime();
} while (start + interval >= end);
}
}
通过内存屏障可以防止指令重排对结果造成影响
内存屏障规则: