Skip to content

14_阻塞队列

首先它是一个队列,而队列的特点是先进先出,所以阻塞队列的特点就是先进先出,其次它是一个阻塞队列,所以阻塞队列的特点就是阻塞,当队列满了,再往队列里面add元素的时候就会被阻塞,当队列为空时,从队列里面take元素的时候也会被阻塞.

  • BlockingQueue接口通过继承Queue,Collection,Iterate接口,增加了阻塞的功能。
  • 阻塞队列的实现类有
    • ArrayBlockingQueue 有界队列
    • LinkedBlockingQueue 无界队列
    • PriorityBlockingQueue 优先级队列
    • DelayQueue 延迟队列
    • SynchronousQueue 同步队列
    • LinkedTransferQueue 链表传输队列
    • LinkedBlockingDeque 双端队列

阻塞队列的方法

  • add(E e):将指定元素插入此队列中,如果没有可用空间,将抛出IllegalStateException异常。
  • remove():获取并移除此队列的头元素,如果队列为空,将抛出NoSuchElementException异常。
  • offer(E e):将指定元素插入此队列中,如果没有可用空间,将返回false。
  • poll():获取并移除此队列的头元素,如果队列为空,将返回null。
  • put(E e):将指定元素插入此队列中,如果没有可用空间,将阻塞等待。
  • take():获取并移除此队列的头元素,如果队列为空,将阻塞等待。
  • peek():获取但不移除此队列的头元素,如果队列为空,将返回null。
  • size():返回此队列中的元素个数。

阻塞队列的使用

java
public class BlockingQueueExample {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    queue.put(i);
                    System.out.println(Thread.currentThread().getName() + " 生产 " + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Producer").start();

        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    Integer take = queue.take();
                    System.out.println(Thread.currentThread().getName() + " 消费 " + take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Consumer").start();
    }
}