package others;
/**
* 指令重排: 代码执行顺序与预期不一致
* 目的: 提高性能
* @author
*
*/
public class HappenBefore {
//变量一
private static int a = 0;
//变量二
private static boolean flag = false;
public static void main(String[] args) throws InterruptedException {
for(int i=0; i<100; i++) {
a = 0; flag = false;
//线程一更改数据
Thread t1 = new Thread(()->{
a = 1;
flag =true;
});
//线程二 读取数据
Thread t2 = new Thread(()->{
if(flag) {
a *= 1;
}
if(a == 0) {
System.out.println("happen before a->"+a);
}
});
t1.start();
t2.start();
//合并线程(线程的插队)
t1.join();
t2.join();
}
}
}
多线程 可重入锁(HappenedBefore)
最新推荐文章于 2022-08-23 21:50:53 发布