1.定义各类型自增方法
static class ClickNumber {
// synchronized方法
int number = 0;
public synchronized void add_synchronized() {
number++;
}
// atomicInteger
AtomicInteger atomicInteger = new AtomicInteger();
public void add_atomicInteger() {
atomicInteger.incrementAndGet();
}
// atomicLong
AtomicLong atomicLong = new AtomicLong();
public void add_atomicLong() {
atomicLong.incrementAndGet();
}
// longAccumulator
LongAccumulator longAccumulator = new LongAccumulator(Long::sum, 0);
public void add_longAccumulator() {
longAccumulator.accumulate(1);
}
// longAdder
LongAdder longAdder = new LongAdder();
public void add_longAdder() {
longAdder.increment();
}
}
2.编写测试方法
开启50个线程,每个线程执行100 * 10000次

该博客对比了不同并发计数方式的性能,包括synchronized、AtomicInteger、AtomicLong、LongAccumulator和LongAdder。通过开启50个线程,每个线程执行100万次操作,结果显示LongAdder在并发性能上表现最佳。
最低0.47元/天 解锁文章
675

被折叠的 条评论
为什么被折叠?



