大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
/** * 验证指令重排的案例 * 顺序执行下,x和y不可能同时为0,如果出现了同时为0,则说明发生了指令重排。 */
public class InstructionRearrangement {
static int a = 0, b = 0, x = 0, y = 0;
public static void main(String[] args) throws InterruptedException {
while (true) {
Thread one = new Thread(() -> {
a = 1;
x = b;
});
Thread other = new Thread(() -> {
b = 1;
y = a;
});
one.start();
other.start();
one.join();
other.join();
//没有指令重排,x和y不可能同时为0
if (x == 0 && y == 0) {
System.out.println("x=" + x + ",y=" + y);
}
a = 0;
b = 0;
x = 0;
y = 0;
}
}
}
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/180936.html原文链接:https://javaforall.net