指令重排
【小城贝尔】
指令重排无依赖,虚拟优化硬件在。
线程运行速度快,写回寄存也会菜。
package concurrently.HappenBefore;
public class HappenBefor {
static int a = 0 ;
static boolean b = false;
public static void main(String[] args) throws Exception{
for (int i = 0; i < 1000 ; i ++){
a = 0;
b = true;
Thread t = new Thread(()->{
a = 1 ;
b = true;
});
Thread t2 = new Thread(()->{
if(b){
a *= 1;
}
// 发生了指令重排
if(a == 0){
System.out.println("a ====>"+a);
}
});
t.start();
t2.start();
}
/*
a ====>0
a ====>0
a ====>1
a ====>1
*/
}
}