简介
ArrayBlockingQueue是一个FIFO的有界阻塞队列。array数组Object[] items
存储,采用生产者-消费者模式入队和出队,支持线程公平策略。
Queue接口
抛异常1方法 | 不抛异常接口 |
---|---|
add | offer |
remove | poll |
element | peek |
入队
public boolean offer(E e) {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
if(count == items.length)
return false;
else {
enqueue(e);
return true;
}
} finally {
lock.unlock();
}
}
offer方法是个非阻塞的方法,一旦判断出数组满则立即返回false。add方法调用了offer方法,如果offer方法返回false,则抛出异常。
put方法提供了入队的阻塞形式。
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
notFull
用于保存当前请求入队的线程到等待链表中;notEmpty
用于将阻塞的线程唤醒。
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;
notEmpty.signal();
}
出队
非阻塞:
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
阻塞:
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
return dequeue();
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
private E dequeue() {
// assert lock.getHoldCount() == 1;
// assert items[takeIndex] != null;
final Object[] items = this.items;
@SuppressWarnings("unchecked")
E x = (E) items[takeIndex];
items[takeIndex] = null;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
锁
出队和入队共享一个ReentrantLock
.
迭代器
Iterator
和ListIterator
,前者主要用于遍历和删除,后者还可以用于插入元素。
- add会抛出
IllegalStateException
,remove和element会抛出NoSuchElementException
. ↩