LinkedBlockingQueue是Java中基于链表的阻塞队列,支持有界和无界模式,常用put/take实现生产者-消费者模型,适用于线程池任务队列及多线程解耦通信。

在Java中,LinkedBlockingQueue 是一个基于链表结构的阻塞队列,常用于多线程环境下的任务调度或生产者-消费者模型。它实现了 BlockingQueue 接口,支持在插入和移除操作时进行阻塞,非常适合线程安全的数据传递。
你可以创建无界或有界的 LinkedBlockingQueue:
// 创建无界队列 LinkedBlockingQueue<String> unboundedQueue = new LinkedBlockingQueue<>(); // 创建有界队列,最多容纳10个元素 LinkedBlockingQueue<Integer> boundedQueue = new LinkedBlockingQueue<>(10);
LinkedBlockingQueue 提供了多种线程安全的操作方法,适合不同需求:
插入元素
立即学习“Java免费学习笔记(深入)”;
put(e):将元素插入队列,如果队列满则阻塞等待offer(e):立即返回 true/false,不会阻塞offer(e, timeout, unit):等待指定时间尝试插入获取并移除元素
take():取出队首元素,队列为空时阻塞等待poll():立即返回元素或 null(如果为空)poll(timeout, unit):最多等待指定时间
// 生产者线程示例
new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
boundedQueue.put(i);
System.out.println("生产: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
// 消费者线程示例
new Thread(() -> {
try {
while (true) {
Integer num = boundedQueue.take();
System.out.println("消费: " + num);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
LinkedBlockingQueue 特别适用于以下情况:
注意:若使用无界队列,要警惕内存溢出风险;选择有界队列能更好控制系统资源。
基本上就这些,用好 put/take 方法就能构建稳定的生产者-消费者系统。以上就是如何在Java中使用LinkedBlockingQueue的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号