LongAdder和LongAccumulator

	//其初始值只能是0
    LongAdder longAdder = new LongAdder();
    
    public Long addLongAdder() {
        longAdder.increment();
        return longAdder.longValue();
    }

    /**
     * 构造函数  LongAccumulator(LongBinaryOperator accumulatorFunction,long identity)
     * @param accumulatorFunction 函数式接口,可以使用匿名内部类或lambda表达式实现其抽象方法
     * 							  抽象方法 long applyAsLong(long left, long right);
     * @param identity 初始值
     * @return 运算结果
     */
    LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x * y, 0);

    public Long addLongAccumulator() {
        longAccumulator.accumulate(1);
        return longAccumulator.get();
    }

下面使用AtomicInteger中cas自旋的方式,一万个线程参与计算耗时

    public static void main(String[] args) throws InterruptedException {
        //result初始值为零
        AtomicInteger result = new AtomicInteger(0);
        int size = 10000;
        CountDownLatch countDownLatch = new CountDownLatch(size);
        Instant startTime = Instant.now();
        for (int i = 0; i < size; i++) {
            new Thread(() -> {
                while (!result.compareAndSet(result.get(), result.get() + 5)){
                    System.out.println("i1 = " + result.get());
                }
                countDownLatch.countDown();
            }, "t_" + i).start();
        }
        countDownLatch.await();
        System.out.println("总耗时毫秒数:" + Duration.between(startTime, Instant.now()).toMillis());
        System.out.println("打印结果值 = " + result.get());
    }

AtomicInteger的方式执行结果如下:
i1 = 5
i1 = 560
i1 = 1195
i1 = 25905
i1 = 34290
i1 = 34710
总耗时毫秒数:1977
打印结果值 = 50000


注释打印的耗时代码再测 //System.out.println("i1 = " + result.get());
总耗时毫秒数:1484
打印结果值 = 50000

下面使用LongAccumulator分散热点的方式,一万个线程参与计算耗时

    public static void main(String[] args) throws InterruptedException {
        //初始值为零
        LongAccumulator longAccumulator = new LongAccumulator((left, right) -> left + right,0);
        int size = 10000;
        CountDownLatch countDownLatch = new CountDownLatch(size);
        Instant startTime = Instant.now();
        for (int i = 0; i < size; i++) {
            new Thread(() -> {
                longAccumulator.accumulate(5);
                countDownLatch.countDown();
            }, "t_" + i).start();
        }
        countDownLatch.await();
        System.out.println("总耗时毫秒数:" + Duration.between(startTime, Instant.now()).toMillis());
        System.out.println("打印结果值 = " + longAccumulator.get());
    }

LongAccumulator的方式执行结果如下:
总耗时毫秒数:618
打印结果值 = 50000

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值