Java 阻塞队列

简介

Java 的阻塞队列是应用在多线程中,尤其适合生产者和消费者模式,阻塞队列支持阻塞操作,线程安全,已经实现了繁琐的简单锁和重入锁。

阻塞队列框架

BlockingQueue框架


特性

  1. BlockingQueue不接受 null 元素。
    试图 add、put或 offer一个 null元素时,某些实现会出 NullPointerException。null被用作指示 poll操作失败的警戒值。
  2. BlockingQueue可以是限定容量的。
    它在任意给定时间都可以有一个 remainingCapacity,超出此容量,便无法无阻塞地 put额外的元素。没有任何内部容量约束的 BlockingQueue总是报告 Integer.MAX_VALUE的剩余容量。
  3. BlockingQueue 实现主要用于生产者-使用者队列。
    即一个线程向队列添加数据,另外一个线程向队列获取数据。
  4. BlockingQueue 实现是线程安全的。
    所有排队方法都可以使用内部锁定或其他形式的并发控制来自动达到它们的目的,内部实现了繁琐的线程锁机制。

主要方法

操作方式一直阻塞超时退出抛出异常返回值
插入put(e)offer(timeout,unit)add(e)offer(e)
移除take(e)poll(timeout,unit)remove()poll()
检查element()peek()

ArrayBlockingQueue

  • 特性
    1. 基于数组的阻塞队列,按FIFO原则对元素进行排序。
      队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。新元素插入到队列的尾部,队列检索操作则是从队列头部开始获得元素。
    2. 容量大小固定。
      一旦创建了这样的缓存区,就不能再增加其容量。试图向已满队列中放入元素会导致放入操作受阻塞;试图从空队列中检索元素将导致类似阻塞。
    3. 可选公平策略。
      默认情况下不保证按FIFO顺序访问队列,可以通过创建队列的时设置fair为true,从而允许FIFO顺序访问队列。

公平策略:所谓公平访问队列是指阻塞的所有生产者线程或消费者线程,当队列可用时,可以按照阻塞的先后顺序访问队列,即先阻塞的生产者线程,可以先往队列里插入元素,先阻塞的消费者线程,可以先从队列里获取元素。

通过以下方式来创建可公平访问的队列。

ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(500,true);

实际项目中的应用

  在smack中就是用到了ArrayBlockingQueue阻塞队列来存储要发送的消息,一个线程负责从队列中获取消息然后发送出去,其他的线程向队列中插入消息。

初始化阻塞队列:

protected PacketWriter(XMPPConnection connection) {
        this.queue = new ArrayBlockingQueue<Packet>(500, true);
        this.connection = connection;
        init();
    }

从队列中获取消息:

private Packet nextPacket() {
        Packet packet = null;
        // Wait until there's a packet or we're done.
        while (!done && (packet = queue.poll()) == null) {
            try {
                synchronized (queue) {
                    queue.wait();
                }
            }
            catch (InterruptedException ie) {
                // Do nothing
            }
        }
        return packet;
    }

向队列中插入消息:

public void sendPacket(Packet packet) {
        if (!done) {
            // Invoke interceptors for the new packet that is about to be sent. Interceptors
            // may modify the content of the packet.
            connection.firePacketInterceptors(packet);

            try {
                queue.put(packet);
            }
            catch (InterruptedException ie) {
                ie.printStackTrace();
                return;
            }
            synchronized (queue) {
                queue.notifyAll();
            }

            // Process packet writer listeners. Note that we're using the sending
            // thread so it's expected that listeners are fast.
            connection.firePacketSendingListeners(packet);
        }
    }

插入消息的时候,就用到了put()方法,如果该队列满了,会一直阻塞,直到有空闲。

LinkedBlockingQueue

  1. 一个基于已链接节点的、范围任意的 blocking queue。
  2. 此队列按 FIFO(先进先出)排序元素。
  3. 默认长度 Integer.MAX_VALUE。
  4. 动态地创建链接节点。
    但是为了防止队列过度扩展,构造该队列时可设置固定容量大小。

实际项目应用

也是smack项目中的使用。
MAX_PACKETS = 65536

protected PacketCollector(Connection conection, PacketFilter packetFilter) {
        this.conection = conection;
        this.packetFilter = packetFilter;
        this.resultQueue = new LinkedBlockingQueue<Packet>(MAX_PACKETS);
    }

超时的操作:

public Packet nextResult(long timeout) {
        long endTime = System.currentTimeMillis() + timeout;
        do {
            try {
                return resultQueue.poll(timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) { /* ignore */ }
        } while (System.currentTimeMillis() < endTime);
        return null;
    }

一直阻塞的操作:

public Packet nextResult() {
        while (true) {
            try {
                return resultQueue.take();
            } catch (InterruptedException e) { /* ignore */ }
        }
    }

从上面的使用来看,smack充分的利用了阻塞队列。

阻塞队列的实现原理

在了解原理之前,需要知道Java中的锁机制和种类,重点了解可重入锁。

可重入锁:ReentrantLock

### Java BlockingQueue 的使用方法及示例 #### 什么是BlockingQueue? `BlockingQueue` 是 Java 并发包 `java.util.concurrent` 中的一个接口,它代表了一个线程安全的队列。通过该接口,多个线程可以在不影响数据一致性的前提下向队列中插入或移除元素[^2]。 当一个线程尝试从空的 `BlockingQueue` 获取元素时,或者另一个线程尝试向已满的 `BlockingQueue` 插入元素时,这些操作可能会阻塞当前线程,直到条件满足为止[^1]。 --- #### 常见的BlockingQueue实现类 以下是几种常见的 `BlockingQueue` 实现类及其特点: - **ArrayBlockingQueue**: 由数组支持的有界阻塞队列,按 FIFO(先进先出)顺序存储数据。 - **LinkedBlockingQueue**: 可选容量上限的基于链表结构的无界阻塞队列,默认情况下大小无限大。 - **PriorityBlockingQueue**: 支持优先级排序的无界阻塞队列。 - **SynchronousQueue**: 不存储任何元素的特殊阻塞队列,每一个插入操作都必须等待另一个线程的对应移除操作[^3]。 --- #### 方法分类 `BlockingQueue` 提供了几种不同行为的方法来处理可能发生的异常情况: | 方法名 | 抛出异常 | 返回特定值 | 超时返回布尔值 | 阻塞直至成功 | |--------------|------------------|----------------|--------------------|-------------------| | add(e) | yes | no | no | no | | offer(e) | no | yes | no | no | | put(e) | no | no | no | yes | | poll(time) | no | yes | yes | no | | take() | no | no | no | yes | 上述表格展示了每种方法的行为差异,开发者可以根据具体需求选择合适的方式[^4]。 --- #### 示例代码 下面是一个简单的生产者-消费者模式的例子,展示如何利用 `BlockingQueue` 来同步两个线程之间的通信。 ```java import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ProducerConsumerExample { public static void main(String[] args) throws InterruptedException { // 创建一个容量为10的阻塞队列 BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10); Thread producerThread = new Thread(() -> { try { int value = 0; while (true) { System.out.println("Producing: " + value); queue.put(value++); // 如果队列满了,则此操作会阻塞 Thread.sleep(1000); // 模拟生产时间 } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); Thread consumerThread = new Thread(() -> { try { while (true) { Integer consumedValue = queue.take(); // 如果队列为空,则此操作会阻塞 System.out.println("Consumed: " + consumedValue); Thread.sleep(2000); // 模拟消费时间 } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); producerThread.start(); consumerThread.start(); // 让主线程运行一段时间后再中断子线程 Thread.sleep(10000); producerThread.interrupt(); consumerThread.interrupt(); } } ``` 在这个例子中: - 生产者线程不断生成整数并将其加入到队列中; - 消费者线程则不断地从队列中取出整数进行处理; - 当队列达到其最大容量时,`put()` 方法会使生产者线程暂停执行;同样地,当队列为空时,`take()` 方法会让消费者线程进入等待状态[^5]。 --- #### 总结 `BlockingQueue` 是一种非常强大的工具,在多线程环境下尤其有用。它可以有效简化诸如生产者-消费者模型之类的复杂场景中的编程工作量,并提供多种灵活的操作方式以适应不同的业务逻辑需求。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值