- 一个常用的并发队列,链表实现
有效构造函数
- 构造函数1
public LinkedBlockingQueue(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node<E>(null);
}
设置了queue的容量,队首=队尾=首节点( new Node<E>(null) )
看一下这个node的结构,一个很简单的链表节点:
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
- 构造函数2
public LinkedBlockingQueue(Collection<? extends E> c) {
this(Integer.MAX_VALUE);
final ReentrantLock putLock = this.putLock;
putLock.lock(); // Never contended, but necessary for visibility
try {
int n = 0;
for (E e : c) {
if (e == null)
throw new NullPointerException();
if (n == capacity)
throw new IllegalStateException("Queue full");
enqueue(new Node<E>(e));
++n;
}
count.set(n);
} finally {
putLock.unlock();
}
}
队列容量是Integer.MAX_VALUE,将入参collection中的元素都添加到队列中