LongAdder 测试

时间:2022-12-17 02:25:53
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder; /**
* @Author: zdz
* @Date: 2019/3/22 2:32 PM
* @Version 1.0
*/
public class Test {
private static final Logger log = LoggerFactory.getLogger(Test.class); private static int clientTotal=1000000;
private static int threadTotal=200; //使用LongAdder
public static LongAdder count=new LongAdder();
//使用Atomic
// public static AtomicLong count=new AtomicLong(0); public static void main(String[] args) throws InterruptedException { long l = System.currentTimeMillis();
ExecutorService executorService = Executors.newFixedThreadPool(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for(int i=0;i<clientTotal;i++){
executorService.execute(() -> {
try {
add();
} catch (Exception e) {
e.printStackTrace();
log.error("Exception",e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
log.info("count:{}",count);
executorService.shutdown();
System.out.println(System.currentTimeMillis()-l);
} private static void add(){
//使用LongAdder类
count.increment();
//使用Atomic
// count.getAndIncrement();
} }