java concurrent 之 LinkedBlockingQueue

java concurrent 之 LinkedBlockingQueue

一个基于已链接节点的、范围任意的 blocking queue。此队列按 FIFO(先进先出)排序元素。队列的头部 是在队列中时间最长的元素。队列的尾部 是在队列中时间最短的元素。新元素插入到队列的尾部,并且队列获取操作会获得位于队列头部的元素。链接队列的吞吐量通常要高于基于数组的队列,但是在大多数并发应用程序中,其可预知的性能要低。

可选的容量范围构造方法参数作为防止队列过度扩展的一种方法。如果未指定容量,则它等于 Integer.MAX_VALUE。除非插入节点会使队列超出容量,否则每次插入后会动态地创建链接节点。


BlockingQueue unbounded = new LinkedBlockingQueue();
BlockingQueue bounded   = new LinkedBlockingQueue(1024);

bounded.put("Value");

String value = bounded.take();

可以采用下面的实例进行尝试 take() pull() remove() offer() add()等方法的区别

package com.viashare.linkedblockingqueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by Jeffy on 15/12/11.
 */
public class LinkedBlockingQueueMain {

    public static void main(String[] args) throws InterruptedException {

        LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<>(2);
        new Thread(new ProducerTask(linkedBlockingQueue)).start();
        new Thread(new ConsumerTask(linkedBlockingQueue)).start();
        Thread.currentThread().sleep(10000);
        System.err.println("finished");
    }

    static class ProducerTask implements Runnable {

        private BlockingQueue queue;

        public ProducerTask(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(2000);

                queue.put("name1");
                Thread.sleep(2000);
                queue.put("name2");
                Thread.sleep(2000);
                System.err.println(queue.offer("name3"));
                System.err.println(queue.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class ConsumerTask implements Runnable {

        private BlockingQueue queue;

        public ConsumerTask(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                   String info =  queue.peek();
                    System.err.println(info);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

}


你可能感兴趣的:(java concurrent 之 LinkedBlockingQueue)