http://m.blog.csdn.net/blog/luoyuyou/38265817
java
ArrayBlockingQueue是一个基于数组和锁的有容量限制的阻塞队列,事实上它的阻塞能力来自于锁和条件队列。数组
咱们对关键代码展开:this
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { checkNotNull(e); long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == items.length) { if (nanos <= 0) return false; nanos = notFull.awaitNanos(nanos); } enqueue(e); return true; } finally { lock.unlock(); } }这里的过程比较简单也比较熟悉,无非是先获取锁,查看当前个数和容量对比,以后会限时阻塞而后入队列,发送信号而且返回true,最后释放锁。
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(); } }与offer的过程相似,区别只是会从队列中取出节点。
ArrayBlockingQueue的特色是容量限制,而且锁范围较大,因此大多数状况下可能不是好的选择。
spa