输出:
结果:50000000,耗时(ms):206 结果:50000000,耗时(ms):105 结果:50000000,耗时(ms):107 结果:50000000,耗时(ms):107 结果:50000000,耗时(ms):105 结果:50000000,耗时(ms):99 结果:50000000,耗时(ms):106 结果:50000000,耗时(ms):102 结果:50000000,耗时(ms):106 结果:50000000,耗时(ms):102平均耗时:100毫秒
代码中new LongAdder()创建一个LongAdder对象,内部数字初始值是0,调用increment()方法可以对LongAdder内部的值原子递增1。reset()方法可以重置LongAdder的值,使其归0。
方式4:LongAccumulator实现LongAccumulator介绍
LongAccumulator是LongAdder的功能增强版。LongAdder的API只有对数值的加减,而LongAccumulator提供了自定义的函数操作,其构造函数如下:
/** * accumulatorFunction:需要执行的二元函数(接收2个long作为形参,并返回1个long) * identity:初始值 **/ public LongAccumulator(LongBinaryOperator accumulatorFunction, long identity) { this.function = accumulatorFunction; base = this.identity = identity; }示例代码:
package com.itsoku.chat32; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.LongAccumulator; import java.util.concurrent.atomic.LongAdder; /** * 跟着阿里p7学并发,微信公众号:javacode2018 */ public class Demo4 { static LongAccumulator count = new LongAccumulator((x, y) -> x + y, 0L); public static void incr() { count.accumulate(1); } public static void main(String[] args) throws ExecutionException, InterruptedException { for (int i = 0; i < 10; i++) { count.reset(); m1(); } } private static void m1() throws ExecutionException, InterruptedException { long t1 = System.currentTimeMillis(); int threadCount = 50; CountDownLatch countDownLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { new Thread(() -> { try { for (int j = 0; j < 1000000; j++) { incr(); } } finally { countDownLatch.countDown(); } }).start(); } countDownLatch.await(); long t2 = System.currentTimeMillis(); System.out.println(String.format("结果:%s,耗时(ms):%s", count.longValue(), (t2 - t1))); } }输出:
结果:50000000,耗时(ms):138 结果:50000000,耗时(ms):111 结果:50000000,耗时(ms):111 结果:50000000,耗时(ms):103 结果:50000000,耗时(ms):103 结果:50000000,耗时(ms):105 结果:50000000,耗时(ms):101 结果:50000000,耗时(ms):106 结果:50000000,耗时(ms):102 结果:50000000,耗时(ms):103平均耗时:100毫秒
LongAccumulator的效率和LongAdder差不多,不过更灵活一些。
调用new LongAdder()等价于new LongAccumulator((x, y) -> x + y, 0L)。
从上面4个示例的结果来看,LongAdder、LongAccumulator全面超越同步锁及AtomicLong的方式,建议在使用AtomicLong的地方可以直接替换为LongAdder、LongAccumulator,吞吐量更高一些。
java高并发系列目录
阿里p7一起学并发,公众号:路人甲java,每天获取最新文章!