阻塞队列BlockingQueue
2020-09-12 本文已影响0人
WLHere
BlockingQueue说明
- 提供对存取的阻塞功能,在存取时适时等待
- 存:如果没有可用空间,则等待直到有空间存储
- 取:如果队列为空,则等待直到队列有值
BlockingQueue方法和结果
Throws Exception | 返回特殊值 | 阻塞 | 超时 | |
---|---|---|---|---|
Insert | add(o) | offer(o) | put(o) | offer(o, timeout,timeunit) |
Remove | remove(0) | poll() | take() | poll(timeout, timeunit) |
Examine | element() | peek() | not applicable | not applicable |
BlockingQueue分类
- ArrayBlockingQueue
- 基于数组实现的有界队列。使用双指针(takeIndex、putIndex)来分指向取和添加元素的位置
- 锁、等待、唤醒通过ReentrantLock实现,分别用notEmpty和notFull的condition来实现等待和唤醒
- 在创建的时候即申请指定大小内存
- 在容量小的情况下,使用ArrayBlockingQueue避免动态创建节点(和LinkedBlockingQueue对比)
- 默认非公平锁,可以设置公平锁
- LinkedBlockingQueue
- 基于单向链表实现的可选有界队列。有头尾指针:head和last
- 锁、等待、唤醒通过ReentrantLock实现。有两个锁takeLock和putLock。takeLock输出notEmpty Condition,putLock输出notFull Condition
- 随着添加元素申请内存;如果不指定大小则为Interger.MAX;
- 在容量大的时候使用LinkedBlockingQueue避免在刚开始就申请大内存(和ArrayBlockingQueue对比)
- 默认非公平锁,不可改变
- PriorityBlockingQueue
- 基于数组实现的无界队列,数组是平衡2叉堆方式的方式。顶点元素小于子节点元素,最小的元素在0位置。
- 可以设置comparator来排序,如果comparator为空则使用对象的默认排序来实现。
- 默认非公平锁,不可改变
- DelayQueue
- 基于PriorityBlockingQueue实现的无界等待队列
- 元素必须实现Delayed接口,返回需要的延迟时间
- 取元素时如果 delay大于0,则等待delay时间。等待之后再次进行取操作。
- 等待机制:使用ReentrantLock.Condition.awaitNanos(long nanosTimeout)
- 默认非公平锁,不可改变
- SynchronousQueue
- 空队列,存取必须是成对的操作,否则进入等待
- 默认非公平锁,可以设置公平锁