
我们在说队列顺序的时候,linkedblockingqueue先进先出的顺序,显示和我们常规的先进再出的理念有所不同。这里我们需要深入到linkedblockingqueue的原理中,去讨论这种顺序机制的存在。接下来我们会从其主要属性、构造函数以及继承结构中,为大家找寻linkedblockingqueu的原理。
1.主要属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | private final int capacity;
private final AtomicInteger count = new AtomicInteger();
transient Node<E> head;
private transient Node<E> last;
private final ReentrantLock takeLock = new ReentrantLock();
private final Condition notEmpty = takeLock.newCondition();
private final ReentrantLock putLock = new ReentrantLock();
private final Condition notFull = putLock.newCondition();
|
(1)capacity,有容量,可以理解为LinkedBlockingQueue是有界队列
(2)head, last,链表头、链表尾指针
(3)takeLock,notEmpty,take锁及其对应的条件
(4)putLock, notFull,put锁及其对应的条件
(5)入队、出队使用两个不同的锁控制,锁分离,提高效率
2.构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public LinkedBlockingQueue() {
this (Integer.MAX_VALUE);
}
public LinkedBlockingQueue(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this .capacity = capacity;
last = head = new Node<E>( null );
}
public LinkedBlockingQueue(Collection<? extends E> c) {
this (Integer.MAX_VALUE);
final ReentrantLock putLock = this .putLock;
putLock.lock();
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();
}
}
|
3.继承结构

以上就是linkedblockingqueue在java中的原理展示,我们通过其函数组成和结构示意图,对linkedblockingqueue能够有大体上的了解,尤其是我们说它是链表结构,想必现在大家已经能够理解原理了。