BlockingQueue接口

版权声明:本文为博主原创文章,可以随意转载,但是必须在开头标明出处。 https://blog.csdn.net/qq_29951983/article/details/82112609

BlockingQueue是一个可以设置容量的阻塞队列的接口,如果没有进行容量限制则为Integer.MAX_VALUE的;
BlockingQueue实现主要用于生产者 - 消费者队列,但另外支持Collection接口。
已知的实现类有
ArrayBlockingQueue
DelayQueue
LinkedBlockingDeque
LinkedBlockingQueue
LinkedTransferQueue
PriorityBlockingQueue
SynchronousQueue

BlockingQueue的方法有四种形式

* 抛出异常 指定值 阻塞 超出时间
插入 add(e) offer(e) put(e) offer(e, time, unit)
移除 remove() poll() take() poll(time, unit)
检查 element() peek()

抛出异常

  • add(e):将指定的元素插入到该队列的尾部,如果队列没满就插入到末尾,并且返回true,当队列满了,就抛出异常Exception in thread "main" java.lang.IllegalStateException: Queue full
  • remove(Object o):从此队列中移除指定元素的单个实例,如果存在返回true,否则返回false;
  • element():取得但不删除此队列的头部。此方法与peek的不同之处仅在于,如果此队列为空,则抛出异常;

指定值

  • offer(e):如果该队列容量没有满,则将指定的元素插入此队列,成功时返回true,如果当前没有可用空间则返回false。
  • poll():检索并删除此队列的头部,如果此队列为空,则返回null,返回值是已经删除的头部。
  • peek():检索但不移除此队列的头部,如果此队列为空,则返回null。

阻塞

  • put(e):将指定的元素插入此队列,等待空间变为可用。会一直阻塞当前线程。
  • take():检索并删除此队列的头部,如果队列是空的,线程就会等待,直到队列里有元素才返回。

超出时间

  • offer(e, time, unit): 第二个参数是时间,第三个参数是时间单位,如果在等待的时间内,队列已经满了,就插不进去了,就会返回false。如果没满就忽略等待时间,直接插入,该方法也是线程阻塞的;
  • poll(time, unit):和上面同理;
final BlockingQueue<String> basket = new LinkedBlockingQueue<String>(2);
        basket.add("111");
        basket.add("222");

        try {
            new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    basket.poll();
                    System.out.println("MyClass.run");
                }
            }.start();
            boolean offer = basket.offer("333", 5000, TimeUnit.MILLISECONDS);
            System.out.println(offer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

参考链接

LinkedBlockingQueue

ArrayBlockingQueue

深入剖析java并发之阻塞队列LinkedBlockingQueue与ArrayBlockingQueue

猜你喜欢

转载自blog.csdn.net/qq_29951983/article/details/82112609