//其初始值只能是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