当前位置:网站首页>多线程并发下的指令重排问题
多线程并发下的指令重排问题
2022-07-29 05:27:00 【魔道不误砍柴功】
在多线程并发情况下,指令重排会出现问题,先看下面一个例子:
public class DemoCount {
public static int r1, r2, x, y;
public static void main(String[] args) throws InterruptedException {
boolean f1, f2, f3, f4;
f1 = f2 = f3 = f4 = false;
int count = 0;
while (true) {
r1 = r2 = x = y = 0;
Thread t1 = new Thread(() -> {
x = 1;
r1 = y;
});
Thread t2 = new Thread(() -> {
y = 1;
r2 = x;
});
t1.start();
t2.start();
t1.join();// 确保线程0、1能够执行完main线程打印后面的输出结果
t2.join();// 确保线程0、1能够执行完main线程打印后面的输出结果
++count;
if (r1 == 0 & r2 == 1 & !f1) {
System.out.println("第" + count + "次出现结果: r1=" + r1 + ":r2=" + r2);
f1 = true;
}
if (r1 == 1 & r2 == 0 & !f2) {
System.out.println("第" + count + "次出现结果: r1=" + r1 + ":r2=" + r2);
f2 = true;
}
if (r1 == 0 & r2 == 0 & !f3) {
System.out.println("第" + count + "次出现结果: r1=" + r1 + ":r2=" + r2);
f3 = true;
}
if (r1 == 1 & r2 == 1 & !f4) {
System.out.println("第" + count + "次出现结果: r1=" + r1 + ":r2=" + r2);
f4 = true;
}
}
}
}
运行会产生四种结果:
第1次出现结果: r1=0:r2=1
第59次出现结果: r1=1:r2=0
第359000次出现结果: r1=1:r2=1
第47518222次出现结果: r1=0:r2=0
这里说明下,出现 r1=0、r2=0 的情况表示出现了指令重排序,我们可以查看代码,两条代码交换位置其实是不影响结果,所以可以发生重排序,针对单线程来看,这种重排序是没有问题,但是多线程并发情况下就会出现问题,所以r1=r2=0 就是因为多线程情况下发生了指令重排序。
从上面这个例子我们可以通俗易懂的理解什么叫做指令重排。解决这个问题就可以使用原语 volatile 禁止指令重排序,底层通过四条内存屏障指令实现。
边栏推荐
- 注解(Annotation)
- Shell脚本-全局变量、局部变量、环境变量
- 华为交换机CE12808导入导出配置文件
- day14_单元测试&日期常用类&字符串常用类
- day13_ Under multithreading
- Hongke | uses jesd204 serial interface to bridge analog and digital worlds at high speed
- Design and simulation code of 4-bit subtracter based on FPGA
- Multiple IO usage
- Thinking about MySQL taking shell through OS shell
- How to use SFTP command to access SFTP server on the development board
猜你喜欢

day06_类与对象

LDAP简述及统一认证说明

Hongke shares | why EtherCAT is the best solution to improve the performance of the control system?

3、 Wide area communication network

Merkletree builds QT implementation UI

day03_ 1_ Process control

Joint use skills of joiner.on and stream().Map

2022年的软件测试的岗位要求为何越来越高?这其中有什么不可告人的秘密吗?

Hongke share | bring you a comprehensive understanding of "can bus error" (I) -- can bus error and error frame

day12_多线程
随机推荐
Hongke share | FPGA implementation of pass through and store and forward switching delay
多路IO用法
将源码包转换为rpm包
day15_ generic paradigm
day03_ 1_ Process control
apisix健康检查测试
Leetcode question brushing record
Advanced socket programming (options and control information)
What are the advantages of software testing? See how much you know
ping 原理
ss命令详解
Why are the job requirements for software testing in 2022 getting higher and higher? Is there any secret in it?
Conversion of fixed-point number to floating-point number of vivado IP core
如何判断业务被DDoS攻击?又会造成哪些危害?
Huawei switch ce12808 import and export configuration file
centos 部署postgresql 13
超低成本DDoS攻击来袭,看WAF如何绝地防护
自动化测试的生命周期是什么?
软件包设置成——>YUM源
Network Security Learning (I)