ArrayBlockingQueue:该类实现了BlockingQueue接口,采用数组Array作为数据结构,在弹出队列时,采用FIFO的策略,初始化的时候需要手动指定初始大小。接下来看一下部分代码:
/**
*初始化代码
**/
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
通过上面的初始化代码,我们可以看到ArrnotFullayBlockingQueue只有一个锁,不过这个锁可以指定获取锁的策略,(相比较LinkedBlockingQueue类,除了可以指定获取锁的策略外,没有其他条件可以让我选择ArrayBlockingQueue),和LinkedBlockingQueue同样有两个信号条件变量notEmpty和notFull。
入队列方法:
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
insert(e);
} finally {
lock.unlock();
}
}
具体的插入方法:
private void insert(E x) {
items[putIndex] = x;
putIndex = inc(putIndex);//设置下一个放置位置
++count;
notEmpty.signal();
}
这里看一下inc()方法
final int inc(int i) {
return (++i == items.length) ? 0 : i;
}
可以看到这里是一个循环取数的方法,因此ArrayBlockingQueue也是循环利用数组空间,这个相比LinkedBlockingQueue要先进一点,不会产生过多的内存碎片。
弹出操作:
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : extract();
} finally {
lock.unlock();
}
}
具体的弹出方法:
private E extract() {
final Object[] items = this.items;
E x = this.<E>cast(items[takeIndex]);
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}