大家好,又见面了,我是你们的朋友全栈君。
/** * 验证指令重排的案例 * 顺序执行下,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;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/180936.html原文链接:https://javaforall.cn