cpu缓存伪共享

/**
 * @描述
 * @参数 $
 * @返回值 $
 * @创建人 yufeng.lin@ucarinc.com
 * @创建时间 $
 * @修改人和其它信息
 */
public class FadeShare implements Runnable{



    //数组长度
    public  static int arrayLength = 4;
    ///数组
    public static VolatileLong []longs = new VolatileLong[arrayLength];
    //计算次数
    public final static long count_time = 500L * 1000L * 1000L;
    //操作的角标   ---------------------!!!不能声明成静态因为那样代表一个对象,否则线程在用的时候每次都要去主存中加载多余数据在缓存,获取改值进行计算,占用巨大时间
    public final     int opIndex;
    //对数组的元素进行赋值:
    static{
        for (int i = 0; i < longs.length; i++) {
            longs[i] = new FadeShare.VolatileLong();
        }
    }
    public  FadeShare(int i){
        this.opIndex = i;
    }


    /**
     * 设计4个线程,执行同一个计算量 计算前后时间
     * @param args
     * @throws InterruptedException
     */
    public static  void main(String args []) throws InterruptedException {

        //java 准备清空缓存
        Thread.sleep(10000);
        final  long start = System.nanoTime();

        Thread  [] threads = new Thread[arrayLength];
        for(int i = 0 ;i< arrayLength; i++){
            threads[i] = new Thread(new FadeShare(i));
        }

        for (Thread thread : threads){
            thread.start();
        }
        for (Thread thread : threads){
            thread.join();
        }

        System.out.println( System.nanoTime() - start );


    }



    @Override
    public void run() {

        Long i = count_time;
        while ( 0 != --i ){
                longs[opIndex].value = i;

        }


    }

    //48Bit  注释掉后数组剩下 8个字节 以及对象头12 字节 会 加载 3个 到一个缓存行,其它线程执行时候会造成伪共享,只能到内存读取数据
    public final static  class VolatileLong{
        public volatile long value = 0l;
//        public long p1,p2,p3,p4;
//        public int p5;

    }



}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值