ConcurrentLinkedQueue 测试

package com.huang.test.concurrent;

import java.util.concurrent.*;

/**
 * ConcurrentLinkedQueue:
 * size 调用开销大,需要遍历整个队列,所以判断是不是空要用isEmpty,而不是size > 0
 * offer添加元素至队列尾,poll从队列首移除元素, peek返回队列首元素
 */
public class ConcurentLinkedQueueTest {
    public static void main(String[] args) {
        ConcurentLinkedQueueTest clqt = new ConcurentLinkedQueueTest();
        clqt.test();
    }

    private void test() {
        int len = 10;
        ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>();
        ExecutorService exec = Executors.newFixedThreadPool(100);
        for(int i = 0;i < len;i++)
        {
            exec.execute(new MyRunnable(queue, i));
        }
        exec.shutdown();
        try {
            exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        printQueue(queue);
        queue.offer("aaaa");
        queue.offer("bbbb");
        printQueue(queue);
        String v = queue.poll();
        System.out.println("poll:" + v);
        printQueue(queue);
        String peek = queue.peek();
        System.out.println("peek:" + peek);
        printQueue(queue);

    }

    private void printQueue(ConcurrentLinkedQueue queue) {
        System.out.println("queue size:" + queue.size() + "(isEmpty:" + queue.isEmpty() + ")");
        for(String item:queue)
        {
            System.out.println(item);
        }
    }

    class MyRunnable implements Runnable
    {
        private ConcurrentLinkedQueue queue;
        private int sec;
        public MyRunnable(ConcurrentLinkedQueue queue, int sec)
        {
            this.queue = queue;
            this.sec = sec;
        }

        @Override
        public void run() {
            queue.add("vvv" + sec);
        }
    }
}

 

你可能感兴趣的:(java)