码迷,mamicode.com
首页 > 移动开发 > 详细

java 多线程-happendBefore

时间:2019-08-18 09:42:56      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:读取   exce   join   exception   不一致   ted   throw   代码执行   rgs   

指令重排:代码执行顺序与预期不一致
目的:提高性能

下例代码,结束时可能打印指令重排:**
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();

}
}

java 多线程-happendBefore

标签:读取   exce   join   exception   不一致   ted   throw   代码执行   rgs   

原文地址:https://blog.51cto.com/14437184/2430467

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!