ConcurrentLinkedQueue 和CountDownLatch 的使用

ConcurrentLinkedQueue 和CountDownLatch 的使用

package com.chow.queue;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zhouhaiming on 2017-5-26 17:22
 * Email: [email protected]
 *
 * @Description:
 */
public class ConcurrentLinkedQueueTest {
    private static ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
    private static int count = 2; // 線程個數
    //CountDownLatch,一個同步輔助類,在完成一組正在其他線程中執行的操作之前,它允許一個或多個線程一直等待。
    private static CountDownLatch latch = new CountDownLatch(count);

    public static void main(String[] args) throws InterruptedException {
        long timeStart = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(4);
        ConcurrentLinkedQueueTest.offer();
        for (int i = 0; i < count; i++) {
            es.submit(new Poll());
        }
        latch.await(); //使得主線程(main)阻塞直到latch.countDown()爲零才繼續執行
        System.out.println("cost time " + (System.currentTimeMillis() - timeStart) + "ms");
        es.shutdown();
    }

    /**
     * 生產
     */
    public static void offer() {
        for (int i = 0; i < 5; i++) {
            queue.offer(i);
        }
    }


    /**
     * 消費
     */
    static class Poll implements Runnable {
        public void run() {
            // while (queue.size()>0) {
            while (!queue.isEmpty()) {
                System.out.println(queue.poll());
            }
            latch.countDown();
        }
    }
}

/*運行結果:
        costtime 2360ms

        改用while (queue.size()>0)後
        運行結果:
        cost time 46422ms

        結果居然相差那麼大,看了下ConcurrentLinkedQueue的API原來.size()是要遍歷一遍集合的,難怪那麼慢,所以儘量要避免用size而改用isEmpty().*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章