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() 是要遍历一遍集合的.

posted @ 2018-06-05 14:03  Againn  阅读(310)  评论(0编辑  收藏  举报