一)LinkedBlockingDeque<E>简介
LinkedBlockingDeque<E>源码详解(基于jdk1.8.0_162)
1)底层由双链表实现。
2)是一个可以双端操作的阻塞队列(先进先出,先进后出)。
3)创建时,可指定队列初始容量,如未指定,默认为Integer.MAX_VALUE,指定后不能修改。是一个线程安全的队列。
类图:LinkedBlockingDeque<E>继承了AbstractQueue<E>类并实现了BlockingQueue<E>接口。
二)构造方法
1)LinkedBlockingDeque()
创建一个 LinkedBlockingDeque ,容量为 Integer.MAX_VALUE 。
2) LinkedBlockingDeque(int capacity)
创建一个具有给定(固定)容量的 LinkedBlockingDeque 。
public LinkedBlockingDeque() {
this(Integer.MAX_VALUE);
}
public LinkedBlockingDeque(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity; // 指定队列初始容量
}
三)添加
1)boolean add(E e)
在队列末尾插入指定的元素,如队列已满,抛IllegalStateException异常,如添加元素为空,抛NullPointerException异常。
2)void push(E e)
将元素插入此双端队列的头部。
3)void addFirst(E e)
将元素插入此双端队列的头部,如队列已满,抛IllegalStateException异常,如添加元素为空,抛NullPointerException异常。
4)void addLast(E e)
将元素插入此双端队列的尾部,如队列已满,抛IllegalStateException异常,如添加元素为空,抛NullPointerException异常。
public boolean add(E e) {
addLast(e); // 调用了addLast方法
return true;
}
public void push(E e) {
addFirst(e); // 调用了addFirst方法
}
public void addFirst(E e) {
if (!offerFirst(e))
throw new IllegalStateException("Deque full"); // 队列已满,抛异常
}
public void addLast(E e) {
if (!offerLast(e))
throw new IllegalStateException("Deque full"); // 队列已满,抛异常
}
5)boolean offer(E e)
将指定的元素插入此双端队列尾部,插入成功返回true,否则返回false
public boolean offer(E e) {
return offerLast(e);
}
6)boolean offerFirst(E e)
将元素插