java线程缓存刷新的疑问

https://www.jianshu.com/p/3c06ffbf0d52

 

import java.util.concurrent.TimeUnit;

public class VolatileFoo {
    final static int MAX=5;
    static  int init_value=0;
    static int index=0;
    public static void main(String[] args){
        new Thread(()->{
            int localValue=init_value;
            long i=0;
            while (localValue<MAX){
                if(init_value!=localValue){
                    System.out.printf("The init_value is updated to [%d]\n",init_value);
                    localValue=init_value;
                }

//                try {
//                    TimeUnit.NANOSECONDS.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }

//                System.out.println();

                i++;

                index++;

            }

        },"Reader").start();
        new Thread(()->{
            int localValue=init_value;
            while (localValue<MAX) {
                System.out.printf("The init_value will be changed to [%d]\n", ++localValue);
                init_value = localValue;
                try {
                    TimeUnit.SECONDS.sleep(2);    //2秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"Updater").start();
    }
}

打开Thread的休眠那段注释,与不打开的结果不一样。

原因可能是 ,休眠醒来,缓存刷新了

posted @ 2019-05-26 18:23  嘿boom  阅读(375)  评论(0编辑  收藏  举报