阻塞队列LinkedBlockingQueue用法

来源:互联网 发布:微创软件怎么样 编辑:程序博客网 时间:2024/06/05 06:16

在Java多线程应用中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列(先进先出)。Java提供的线程安全的Queue可以分为阻塞队列和非阻塞队列,其中阻塞队列的典型例子是BlockingQueue,非阻塞队列的典型例子是ConcurrentLinkedQueue,在实际应用中要根据实际需要选用阻塞队列或者非阻塞队列。

注:什么叫线程安全?这个首先要明确。线程安全就是说多线程访问同一代码,不会产生不确定的结果。


看其API的时候发现,添加元素的方法竟然有三个:add,put,offer。
1.首先看一下add方法:
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

This implementation returns true if offer succeeds, else throws an IllegalStateException.
LinkedBlockingQueue构造的时候若没有指定大小,则默认大小为Integer.MAX_VALUE,当然也可以在构造函数的参数中指定大小。LinkedBlockingQueue不接受null。
add方法在添加元素的时候,若超出了度列的长度会直接抛出异常:
public static void main(String args[]){
try {
LinkedBlockingQueue queue=new LinkedBlockingQueue(2);

        queue.add("hello");        queue.add("world");        queue.add("yes");    } catch (Exception e) {        // TODO: handle exception        e.printStackTrace();    }}

//运行结果:
java.lang.IllegalStateException: Queue full
at java.util.AbstractQueue.add(Unknown Source)
at com.wjy.test.GrandPather.main(GrandPather.java:12)

2.再来看一下put方法:
Inserts the specified element at the tail of this queue, waiting if necessary for space to become available.
对于put方法,若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间,以加入元素。
public static void main(String args[]){
try {
LinkedBlockingQueue queue=new LinkedBlockingQueue(2);

        queue.put("hello");        queue.put("world");        queue.put("yes");        System.out.println("yes");    } catch (Exception e) {        // TODO: handle exception        e.printStackTrace();    }}

//运行结果:
//在queue.put(“yes”)处发生阻塞
//下面的“yes”无法输出

3.最后看一下offer方法:
Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue’s capacity, returning true upon success and false if this queue is full. When using a capacity-restricted queue, this method is generally preferable to method add, which can fail to insert an element only by throwing an exception.

offer方法在添加元素时,如果发现队列已满无法添加的话,会直接返回false。

public static void main(String args[]){
try {
LinkedBlockingQueue queue=new LinkedBlockingQueue(2);

        boolean bol1=queue.offer("hello");        boolean bol2=queue.offer("world");        boolean bol3=queue.offer("yes");        System.out.println(queue.toString());        System.out.println(bol1);        System.out.println(bol2);        System.out.println(bol3);    } catch (Exception e) {        // TODO: handle exception        e.printStackTrace();    }}

//运行结果:
[hello, world]
true
true
false

好了,竟然说了这么多了,就把从队列中取元素的方法也顺便一说。

从队列中取出并移除头元素的方法有:poll,remove,take。

poll: 若队列为空,返回null。
remove:若队列为空,抛出NoSuchElementException异常。
take:若队列为空,发生阻塞,等待有元素。


由于LinkedBlockingQueue实现是线程安全的,实现了先进先出等特性,是作为生产者消费者的首选,LinkedBlockingQueue 可以指定容量,也可以不指定,不指定的话,默认最大是Integer.MAX_VALUE,其中主要用到put和take方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来。

public class MyClass {    /**     *     * 定义装苹果的篮子     *     */    public class Basket {        // 篮子,能够容纳3个苹果        BlockingQueue<String> basket = new LinkedBlockingQueue<String>(3);        // 生产苹果,放入篮子        public void produce() throws InterruptedException {            // put方法放入一个苹果,若basket满了,等到basket有位置            basket.put("An apple");        }        // 消费苹果,从篮子中取走        public String consume() throws InterruptedException {            // take方法取出一个苹果,若basket为空,等到basket有苹果为止(获取并移除此队列的头部)            return basket.take();        }    }    // 定义苹果生产者    class Producer implements Runnable {        private String instance;        private Basket basket;        public Producer(String instance, Basket basket) {            this.instance = instance;            this.basket = basket;        }        public void run() {            try {                while (true) {                    // 生产苹果                    System.out.println("生产者准备生产苹果:" + instance);                    basket.produce();                    System.out.println("!生产者生产苹果完毕:" + instance);                    // 休眠300ms                    Thread.sleep(300);                }            } catch (InterruptedException ex) {                System.out.println("Producer Interrupted");            }        }    }    // 定义苹果消费者    class Consumer implements Runnable {        private String instance;        private Basket basket;        public Consumer(String instance, Basket basket) {            this.instance = instance;            this.basket = basket;        }        public void run() {            try {                while (true) {                    // 消费苹果                    System.out.println("消费者准备消费苹果:" + instance);                    System.out.println(basket.consume());                    System.out.println("!消费者消费苹果完毕:" + instance);                    // 休眠1000ms                    Thread.sleep(1000);                }            } catch (InterruptedException ex) {                System.out.println("Consumer Interrupted");            }        }    }    public static void main(String[] args) {        MyClass test = new MyClass();        // 建立一个装苹果的篮子        Basket basket = test.new Basket();        ExecutorService service = Executors.newCachedThreadPool();        Producer producer = test.new Producer("生产者001", basket);        Producer producer2 = test.new Producer("生产者002", basket);        Consumer consumer = test.new Consumer("消费者001", basket);        service.submit(producer);        service.submit(producer2);        service.submit(consumer);        // 程序运行5s后,所有任务停止//        try {//            Thread.sleep(1000 * 5);//        } catch (InterruptedException e) {//            e.printStackTrace();//        }//        service.shutdownNow();    }}

当注释掉

Consumer consumer = test.new Consumer("消费者001", basket);service.submit(consumer);

及没有消费者,打印如下:

生产者准备生产苹果:生产者001!生产者生产苹果完毕:生产者001生产者准备生产苹果:生产者002!生产者生产苹果完毕:生产者002生产者准备生产苹果:生产者001生产者准备生产苹果:生产者002!生产者生产苹果完毕:生产者001生产者准备生产苹果:生产者001

验证了上面对于put方法,若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间,以加入元素
同样,注释掉

Producer producer = test.new Producer("生产者001", basket);Producer producer2 = test.new Producer("生产者002", basket);service.submit(producer);service.submit(producer2);
    及没有生产者,打印如下:
消费者准备消费苹果:消费者001

验证了上面对于take方法,若队列为空,发生阻塞,等待有元素。

0 0
原创粉丝点击