注意:在阅读本文之前或在阅读的过程中,需要用到ReentrantLock,内容见《第五章 ReentrantLock源码解析1--获得非公平锁与公平锁lock()》《第六章 ReentrantLock源码解析2--释放锁unlock()》《第七章 ReentrantLock总结》
1、对于ArrayBlockingQueue需要掌握以下几点
2、创建
使用方法:
通过使用方法,可以看出ArrayBlockingQueue支持ReentrantLock的公平锁模式与非公平锁模式,对于这两种模式,查看本文开头的文章即可。
源代码如下:
View Code View Code注意:
3、入队
3.1、public boolean offer(E e)
原理:
使用方法:
源代码:
View Code View Code View Code代码非常简单,流程看注释即可,只有一点注意点:
3.2、public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
原理:
使用方法:
View Code源代码:
View Code注意:
3.3、public void put(E e) throws InterruptedException
原理:
使用方法:
View Code源代码:
View Code
4、出队
4.1、public E poll()
原理:
使用方法:
abq.poll();
源代码:
View Code View Code
4.2、public E poll(long timeout, TimeUnit unit) throws InterruptedException
原理:
使用方法:
View Code源代码:
View Code
4.3、public E take() throws InterruptedException
原理:
使用方法:
View Code源代码:
View Code
总结:
1、具体入队与出队的原理图:这里只说一种情况,见下图,途中深色部分表示已有元素,浅色部分没有元素。
上面这种情况是怎么形成的呢?当队列满了,这时候,队头元素为items[0]出队了,就形成上边的这种情况。
假设现在又要出队了,则现在的队头元素是items[1],出队后就形成下面的情形。
出队后,对头元素就是items[2]了,假设现在有一个元素将要入队,根据inc方法,我们可以得知,他要插入到items[0]去,入队了形成下图:
以上就是整个入队出队的流程,inc方法上边已经给出,这里再贴一遍:
View Code
2、三种入队对比:
3、三种出对对比: