java
package jvm;
/**
* 证明cpu指令是乱序执行的
*
* @author 1
* @version 1.0
* @description: TODO
* @date 2024-07-19 9:31
*/
public class T04_Disorder {
private static int x = 0, y = 0;
private static int 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(new Runnable() {
@Override
public void run() {
//由于线程one先启动,下面这句话让它等一等线程two. 读着可根据自己电脑的实际性能适当调整等待时间.
//shortWait(100000);
a = 1;
x = b;
}
});
Thread other = new Thread(new Runnable() {
@Override
public void run() {
b = 1;
y = a;
}
});
one.start();other.start();
one.join();other.join();
String result = "第" + i + "次 (" + x + "," + y + ")";
//如果cpu是顺序指令执行的,那么上面两个线程,要么a=1则y=1或者b=1则x=1 也就是x和y不可能同时为0 除非 线程没有按照顺序执行
if(x == 0 && y == 0) {
System.err.println(result);
break;
} else {
//System.out.println(result);
}
}
}
public static void shortWait(long interval){
long start = System.nanoTime();
long end;
do{
end = System.nanoTime();
}while(start + interval >= end);
}
}
执行结果: 第1661256次 (0,0)
证明了,cpu指令的确是乱序执行的;