https://blog.csdn.net/gjq_1988/article/details/39520729
测试demo
public class Test {
static int x,y,a,b;
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() {
public void run() {
a = 1;
x = b;
}
});
Thread other = new Thread(new Runnable() {
public void run() {
b = 1;
y = a;
}
});
one.start();
other.start();
one.join();
other.join();
String result = "第" + i + ",x:" + x + ",y:" + y;
//逻辑上是不会出现x=0且y=0的情况,除非存在乱序执行
//就是a = 1;与x = b;换顺序,或者b = 1;与y = a;换顺序
if (x ==0 && y ==0){
System.out.println("出现乱序现象!!");
break;
}else{
System.out.println(result);
}
}
}
/* 打印结果:
第2696121,x:0,y:1
第2696122,x:0,y:1
第2696123,x:0,y:1
第2696124,x:0,y:1
第2696125,x:0,y:1
第2696126,x:0,y:1
出现乱序现象!!
*/
}