为什么需要AtomicInteger原子操作类?
对于Java中的运算操作,例如自增或自减,若没有进行额外的同步操作,在多线程环境下就是线程不安全的。num++解析为num=num+1,明显,这个操作不具备原子性,多线程并发共享这个变量时必然会出现问题。测试代码如下:
/**
* @description: 压测AtomicLong的原子操作性能
*/
public class AtomicLongTest implements Runnable {
private static AtomicLong atomicLong = new AtomicLong(0);
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
atomicLong.incrementAndGet();
}
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(30);
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
es.submit(new AtomicLongTest());
}
es.shutdown();
//保证任务全部执行完
while (!es.isTerminated()) { }
long end = System.currentTimeMillis();
System.out.println("AtomicLong add 耗时=" + (end - start));
System.out.println("AtomicLong add result=" + atomicLong.get());
}
}
/**
* @description: 压测LongAdder的原子操作性能
*/
public class LongAdderTest implements Runnable{
private static LongAdder longAdder = new LongAdder();
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
longAdder.increment();
}
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(30);
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
es.submit(new LongAdderTest());
}
es.shutdown();
//保证任务全部执行完
while (!es.isTerminated()) {
}
long end = System.currentTimeMillis();
System.out.println("LongAdder add 耗时=" + (end - start));
System.out.println("LongAdder add result=" + longAdder.sum());
}
}
在高并发情况下,LongAdder(累加器)比AtomicLong原子操作效率更高,LongAdder累加器是java8新加入的,参考以下压测代码
https://blog.csdn.net/fanrenxiang/article/details/80623884
网友评论