当前位置: 首页 > news >正文

阻塞队列ArrayBlockingQueue与LinkedBlockingQueue

文章目录

  • 前言
  • BlockingQueue
    • BlockingQueue 接口特点
    • 应用场景
  • ArrayBlockingQueue
    • 特点
    • 主要方法
      • 插入元素:
      • 移除元素:
      • 其他方法:
    • 代码示例
  • LinkedBlockingQueue
    • 特点
    • 主要方法
      • 插入元素:
      • 移除元素:
      • 检查元素:
    • 代码示例
  • ArrayBlockingQueue 与LinkedBlockingQueue 区别


前言

在研究线程池时,发现jdk自定义的创建线程池底层调用的ThreadPoolExecutor构造方法中需要填写了无界的LinkedBlockingQueue参数。故此研究了一下该类和它的父接口BlockingDeque。

    public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}

BlockingQueue

BlockingQueue 是 Java 中 java.util.concurrent 包提供的一种接口,用于实现线程安全的队列数据结构。BlockingQueue 通常用于多线程环境中,特别是实现生产者-消费者模式时非常有用。它是一种特殊的队列,提供了阻塞操作,使得在队列为空或满的情况下,相关的操作会自动阻塞,直到条件满足为止。本章主要介绍BlockingDeque和它的实现类ArrayBlockingQueue与LinkedBlockingQueue。

BlockingQueue 接口特点

  • 线程安全:BlockingQueue 的所有操作都是线程安全的,允许多个线程并发地添加或移除元素。
  • 阻塞操作:当队列满时,put 操作会阻塞,直到队列中有可用空间;当队列为空时,take 操作会阻塞,直到队列中有元素。
  • 容量限制:BlockingQueue 可以是有界的(有最大容量限制)或无界的(没有最大容量限制)

应用场景

BlockingQueue 主要用于实现生产者-消费者模式,可以有效地解决多线程间的同步问题。它在以下场景中非常有用:

  1. 任务调度:作为任务队列,存放待处理的任务。
  2. 消息传递:作为消息队列,存放待发送的消息。
  3. 缓存系统:作为缓存队列,存放待处理的数据。

ArrayBlockingQueue

ArrayBlockingQueue 是 Java 中 java.util.concurrent 包提供的一种基于数组结构的有界阻塞队列实现。它是一个线程安全的队列,非常适合用于多线程环境下的同步操作。

特点

  • 有界队列:ArrayBlockingQueue 是一个有界队列,这意味着在创建时需要指定队列的最大容量。一旦队列达到最大容量,就不能再添加新的元素,除非队列中有元素被消费。
  • 线程安全:ArrayBlockingQueue 实现了线程安全机制,可以在多个线程之间安全地共享和操作队列。
  • 阻塞特性:ArrayBlockingQueue 提供了阻塞操作,如 put 和 take 方法。当队列满时,put 方法会阻塞等待队列中有空闲空间;当队列为空时,take 方法会阻塞等待队列中有可用元素。
  • 公平性:ArrayBlockingQueue 支持公平和非公平两种插入策略。公平策略(fairness)保证了按照线程到达的顺序来获取队列的资源,而非公平策略则可能让后到达的线程先获取资源。默认情况下,ArrayBlockingQueue 使用非公平策略。

主要方法

插入元素:

void put(E e):将元素 e 插入队列尾部,如果队列已满则等待直到有空闲空间。
boolean offer(E e):尝试将元素 e 插入队列尾部,如果成功则返回 true,如果队列已满则返回 false。
boolean offer(E e, long timeout, TimeUnit unit):尝试在给定时间内将元素 e 插入队列尾部,如果成功则返回 true,如果超时则返回 false。

移除元素:

E take():从队列头部移除并返回一个元素,如果队列为空则等待直到有可用元素。
E poll():尝试从队列头部移除并返回一个元素,如果队列为空则返回 null。
E poll(long timeout, TimeUnit unit):尝试在给定时间内从队列头部移除并返回一个元素,如果成功则返回元素,如果超时则返回 null。
检查元素:
E peek():返回但不移除队列头部的元素,如果队列为空则返回 null。

其他方法:

int remainingCapacity():返回队列剩余的容量。
int size():返回队列中当前的元素数量。
boolean isEmpty():如果队列为空则返回 true。
boolean contains(Object o):如果队列中包含指定元素则返回 true。
Iterator iterator():返回队列的迭代器。

代码示例

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;public class ArrayBlockingQueueExample {// 创建一个容量为 10 的阻塞队列private static ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(10);public static void main(String[] args) {// 生产者线程Thread producer = new Thread(() -> {try {queue.put("item1");queue.put("item2");queue.put("item3");} catch (InterruptedException e) {Thread.currentThread().interrupt();System.err.println("Producer was interrupted");}});// 消费者线程Thread consumer = new Thread(() -> {try {while (true) {String item = queue.take();System.out.println("Consumed: " + item);TimeUnit.SECONDS.sleep(1); // 使当前线程暂停执行1秒,模拟消费时间}} catch (InterruptedException e) {Thread.currentThread().interrupt();System.err.println("Consumer was interrupted");}});producer.start();consumer.start();}
}

LinkedBlockingQueue

LinkedBlockingQueue 是 Java 中 java.util.concurrent 包提供的一种基于链表结构的阻塞队列实现。它是一个线程安全的队列,主要用于多线程环境下的同步操作,和ArrayBlockingQueue 一样适合用于实现生产者-消费者模式。

特点

  • 可选的容量:LinkedBlockingQueue 可以是无界的(默认情况下),也可以是有界的。如果你在创建时指定了一个容量,则队列将是有界的。
  • 线程安全:LinkedBlockingQueue 内部使用锁来保证线程安全,允许多个线程并发地往队列中添加或从中移除元素。
  • 阻塞特性:LinkedBlockingQueue 提供了阻塞操作,如 put 和 take 方法。当队列满时,put 方法会阻塞等待队列中有空闲空间;当队列为空时,take 方法会阻塞等待队列中有可用元素。
  • 公平性:LinkedBlockingQueue 支持公平和非公平两种插入策略。公平策略(fairness)保证了按照线程到达的顺序来获取队列的资源,而非公平策略则可能让后到达的线程先获取资源。

主要方法

插入元素:

void put(E e):将元素 e 插入队列尾部,如果队列已满则等待直到有空闲空间。
boolean offer(E e):尝试将元素 e 插入队列尾部,如果成功则返回 true,如果队列已满则返回 false。
boolean offer(E e, long timeout, TimeUnit unit):尝试在给定时间内将元素 e 插入队列尾部,如果成功则返回 true,如果超时则返回 false。

移除元素:

E take():从队列头部移除并返回一个元素,如果队列为空则等待直到有可用元素。
E poll():尝试从队列头部移除并返回一个元素,如果队列为空则返回 null。
E poll(long timeout, TimeUnit unit):尝试在给定时间内从队列头部移除并返回一个元素,如果成功则返回元素,如果超时则返回 null。

检查元素:

E peek():返回但不移除队列头部的元素,如果队列为空则返回 null。
其他方法:
int remainingCapacity():返回队列剩余的容量。
int size():返回队列中当前的元素数量。
boolean isEmpty():如果队列为空则返回 true。
boolean contains(Object o):如果队列中包含指定元素则返回 true。
Iterator iterator():返回队列的迭代器。

代码示例

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;public class ArrayBlockingQueueExample {// 创建一个容量为 10 的阻塞队列private static LinkedBlockingQueue<String> queue = new LinkedBlockingQueue <>(10);public static void main(String[] args) {// 生产者线程Thread producer = new Thread(() -> {try {queue.put("item1");queue.put("item2");queue.put("item3");} catch (InterruptedException e) {Thread.currentThread().interrupt();System.err.println("Producer was interrupted");}});// 消费者线程Thread consumer = new Thread(() -> {try {while (true) {String item = queue.take();System.out.println("Consumed: " + item);TimeUnit.SECONDS.sleep(1); // 使当前线程暂停执行1秒,模拟消费时间}} catch (InterruptedException e) {Thread.currentThread().interrupt();System.err.println("Consumer was interrupted");}});producer.start();consumer.start();}
}

ArrayBlockingQueue 与LinkedBlockingQueue 区别

ArrayBlockingQueue 与LinkedBlockingQueue 区别:

  1. ArrayBlockingQueue 底层基于数组实现;
  2. LinkedBlockingQueue 底层基于链表实现;
  3. ArrayBlockingQueue 默认是有界队列;
  4. ArrayBlockingQueue 默认是无界队列 容量为 Integer.MAX_VALUE;
  5. ArrayBlockingQueue 读写采用同一把锁, LinkedBlockingQueue
    锁是读写分离;
  6. LinkedBlockingQueue clear方法 同时清理两把锁
  7. LinkedBlockingQueue使用AtomicInteger计入个数,ArrayBlockingQueue int Count计数
  8. 在自定义创建线程池ThreadPoolExecutor时,任务队列时建议设置为有界队列。
    JDK默认的线程池使用无界的LinkedBlockingQueue作为任务队列,这意味着在高负载情况下,任务队列可能无限增长,直至消耗完系统内存,导致OutOfMemoryError。


http://www.mrgr.cn/news/16782.html

相关文章:

  • 学习记录:js算法(二十):子数组最大平均数 I、无重复字符的最长子串
  • 黑神话悟空-提高画质、防卡顿、修复等各种功能、各种CT表、各种存档、武器包、人物、装备替换等193+MOD合集
  • torch.nn.functional.interpolate(最近邻插值,双线性插值)
  • C语言:字符串存在哪?
  • xxe漏洞
  • 【MySQL】索引使用规则——(覆盖索引,单列索引,联合索引,前缀索引,SQL提示,数据分布影响,查询失效情况)
  • 物联网架构之CDH详解
  • 基于SSM的咖啡馆管理系统
  • 【Godot4.3】MarkDown解析和生成类 - MDdoc
  • 【MyBatis】MyBatis的一级缓存和二级缓存简介
  • 29. 双耳配对
  • FastAPI+Vue3零基础开发ERP系统项目实战课 20240831上课笔记 路径参数
  • OCI编程高级篇(十五) 设置字段数据入口
  • 【Kubernetes知识点问答题】第二篇
  • 【电子数据取证】Linux软件包管理器yum和编辑器vim
  • 【408DS算法题】031基础-判断二叉树是否是平衡二叉树
  • linux文件——文件系统——学习、理解、应用软硬件链接
  • PyTorch 的自动求导与计算图
  • 猫咪浮毛不再乱飞 希喂、霍尼韦尔、352宠物空气净化器功能实测
  • 如何在windows中使用hfd.sh aria2c下载huggingface文件