阻塞队列系列:
为了能更好的理解阻塞队列的源码,本篇我们拿 ArrayBlockingQueue 为例来看看阻塞队列的继承关系。
下图是 ArrayBlockingQueue 的继承关系类图:
1.Queue:队列的顶层接口
public interface Queue<E> extends Collection<E> {
// 入队
boolean add(E e);
boolean offer(E e);
// 出队
E remove();
E poll();
// 队首
E peek();
E element();
}
2.AbstractQueue:中间层
- 所有的 Queue 不是直接实现 Queue,而是直接继承 AbstractQueue
- AbstractQueue 实现了部分方法
- add:对offer进行了封装,若offer为false,则抛异常
- remove:对poll进行了封装,若poll为null,则抛异常
- element:对peek进行了封装,若peek为null,则抛异常
- 实现了clear,清空队列
public abstract class AbstractQueue<E>
extends AbstractCollection<E>
implements Queue<E> {
public boolean add(E e) {
// offer
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
public E element() {
E x = peek();
// peek
if (x != null)
return x;
else
throw new NoSuchElementException();
}
public E remove() {
E x = poll();
// poll
if (x != null)
return x;
else
throw new NoSuchElementException();
}
public boolean addAll(Collection<? extends E> c) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
public void clear() {
// 将所有元素弹出
while (poll() != null)
;
}
}
BlockQueue:阻塞队列
阻塞队列的顶层接口,继承了Queue接口
public interface BlockingQueue<E> extends Queue<E>{
boolean add(E e);
// 注:子类调用remove方法时会调用AbstractQueue#remove()
void put(E e) throws InterruptedException;
E take() throws InterruptedException;
// 阻塞一定时间
boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException;
E poll(long timeout, TimeUnit unit) throws InterruptedException;
// 删除指定与安娜
boolean remove(Object o);
//......
}
在阻塞队列中,上面三组出队入队方法的对比如下:
| 抛异常 | 返回特殊值 | 阻塞(WAITING) | 阻塞一段时间 | |
|---|---|---|---|---|
| 入队(满) | add | offer(false) | put | offer 过超时时间返回 false |
| 出队(空) | remove | poll (null) | take | poll 过超时时间返回 null |
| 队首(空) | element | peek (null) | 暂无 | 暂无 |
- 这些方法保证线程安全的方法都是通过锁,因此在夺锁过程中都可能发生阻塞
- 区别只是在碰见空(满)会让相应线程进入WAITING
本文标题:【JUC源码】阻塞队列:继承关系及接口分析
本文链接:https://blog.quwenai.cn/post/9895.html
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。







还没有评论,来说两句吧...