目的:提高性能
下例代码,结束时可能打印指令重排:**
public class tt {
private static int a=0;
private static boolean flag=false;
public static void main(String[]args) throws InterruptedException
{
//线程1更改数据
Thread t1=new Thread(()->{
a=1;
flag=true;
});
//线程2读取数据
Thread t2=new Thread(()->{
if(flag)
{
a*=1;
}
if(a==0)
{
System.out.println("发生了指令重排"+a);
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}