Java实现阻塞队列
2021/8/14 20:06:01
本文主要是介绍Java实现阻塞队列,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
使用Condition实现简单的阻塞队列
阻塞队列是一种特殊的先进先出队列,它有以下几个特点
1.入队和出队线程安全
2.当队列满时,入队线程会被阻塞;当队列为空时,出队线程会被阻塞。
import java.util.LinkedList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @author: MXD * @date: 2021/8/12 17:10 * @description: 实现简单的阻塞队列 */ public class MyBlockingQueue<E> { /** * 阻塞队列最大容量 */ private int size; /** * 队列底层实现 */ LinkedList<E> list = new LinkedList<>(); ReentrantLock lock = new ReentrantLock(); /** * 队列满的等待条件 */ Condition full = lock.newCondition(); /** * 队列空的等待条件 */ Condition empty = lock.newCondition(); public MyBlockingQueue(int size) { this.size = size; } public void enqueue(E e) throws InterruptedException { lock.lock(); try { // 队列满了,就在full条件上进行等待 while (list.size() == size){ full.await(); } list.add(e); System.out.println("入队:"+e); // 入队之后,就通知在empty条件下等待的线程 empty.signal(); } finally { lock.unlock(); } } public E dequeue() throws InterruptedException { E e; lock.lock(); try { // 队列为空,就在空条件上等待 while (list.size() == 0){ empty.await(); } e = list.removeFirst(); System.out.println("出队:"+e); // 出队之后,就通知在full条件下等待的线程 full.signal(); return e; } finally { lock.unlock(); } } }
测试
package com.md.lock; /** * @author: MXD * @date: 2021/8/12 17:28 * @description: */ public class Test { public static void main(String[] args) { final MyBlockingQueue<Integer> blockingQueue = new MyBlockingQueue<Integer>(2); for (int i = 0; i < 5; i++) { final int data = i; new Thread(new Runnable() { @Override public void run() { try { blockingQueue.enqueue(data); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } for (int i = 0; i < 5; i++) { new Thread(new Runnable() { @Override public void run() { try { blockingQueue.dequeue(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } }
结果
了解更多看这个博客,写的非常不错
https://www.cnblogs.com/takumicx/p/9338983.html
这篇关于Java实现阻塞队列的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求