原子累加器
作者:互联网
package com.lx.top;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* 测试原子累加器
*/
public class Test {
public static void main(String[] args) {
// 一段代码被多次执行,jvm会进行优化
for (int i = 0; i < 5; i++) {
demo(
() -> new AtomicLong(0),
(adder) -> adder.getAndIncrement()
);
}
// 一段代码被多次执行,jvm会进行优化
for (int i = 0; i < 5; i++) {
demo (
() -> new LongAdder(),
adder -> adder.increment()
);
}
}
/**
* @param1 提供累加器
* @param2 执行累加操作
*/
private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
T adder = adderSupplier.get();
List<Thread> tList = new ArrayList<Thread>();
// 4个线程,每人累加50万
for (int i = 0; i < 4; i++) {
tList.add(new Thread(() -> {
for (int j = 0; j < 500000; j++) {
action.accept(adder);
}
}));
}
long start = System.nanoTime();
tList.forEach(t -> t.start());
tList.forEach(t -> {
try {
t.join();
} catch (Exception e) {
e.printStackTrace();
}
});
long end = System.nanoTime();
System.out.println(adder + " cost: " + (end - start)/1000_000 + "ms");
}
}
标签:java,int,累加器,原子,util,adder,new,import 来源: https://blog.csdn.net/lenglovexu/article/details/117441084