ConcurrentLinkedQueue的isEmpty个size方法耗时比较测试
Posted Againn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ConcurrentLinkedQueue的isEmpty个size方法耗时比较测试相关的知识,希望对你有一定的参考价值。
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ConcurrentLinkedQueueTest1 { public static void main(String[] args) throws InterruptedException { int peopleNum = 10000;//吃饭人数 int tableNUm = 10;//饭桌数量 ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();//队列 CountDownLatch count = new CountDownLatch(tableNUm);//计数器 //将吃饭人数放入队列(吃饭的人排队) for(int i = 0;i<peopleNum;i++){ queue.offer("消费者_"+i); } //执行10个线程从队列取出元素(10个饭桌开始供饭) System.out.println("---------------------------------开饭了----------------------------------"); long start = System.currentTimeMillis(); ExecutorService executorService = Executors.newFixedThreadPool(tableNUm); for (int i = 0;i<tableNUm;i++){ executorService.submit(new Dinner("00" + (i+1),queue,count)); } //计数器等待,直到队列为空(所有人吃完) count.await(); long time = System.currentTimeMillis()-start; System.out.println("---------------------------所有人吃完--------------------------"); System.out.println("共耗时:"+time); //停止线程池 executorService.shutdown(); } private static class Dinner implements Runnable{ private String name; private ConcurrentLinkedQueue<String> queue; private CountDownLatch count; public Dinner(String name, ConcurrentLinkedQueue<String> queue, CountDownLatch count) { this.name = name; this.queue = queue; this.count = count; } @Override public void run() { //通过两种方式比较耗时 while(queue.size()>0){ // while(!queue.isEmpty()){ System.out.println("【"+queue.poll() +"】---已吃完...,饭桌编号:"+name); } count.countDown(); } } }
通过上面的测试,得出结论:size()方法比isEmpty()耗时更长,原因是size() 是要遍历一遍集合的.
以上是关于ConcurrentLinkedQueue的isEmpty个size方法耗时比较测试的主要内容,如果未能解决你的问题,请参考以下文章
死磕 java集合之ConcurrentLinkedQueue源码分析
Java并发容器--ConcurrentLinkedQueue