ArrayBlockingQueue:基于数组结构的有界阻塞队列(长度不可变);
实现: ReentrantLock + Condition
应用场景:在线程池中有比较多的应用,生产者消费者场景
工作原理: 基于ReentrantLock保证线程安全,根据Condition实现队列满时的阻塞
源码分析
主要属性
// 使用数组存储元素
final Object[] items;// 取元素的指针
int takeIndex;// 放元素的指针
int putIndex;// 元素数量
int count;// 表示总共存放了多少个对象
final ReentrantLock lock;// 非空条件
private final Condition notEmpty;// 非满条件
private final Condition notFull;
从上面的信息可以看到:
(1)ArrayBlockingQueue是利用数据来
(2)通过放指针和取指针来标记下一次操作的位置;
(3)利用重入锁来保证并发安全;
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();
}
通过构造方法我们可以得出以下两个结论:
(1)capacity: capacity 表示数组的大小。
(2)fair:表示是否为公平的阻塞队列,默认情况下构造的是非公平的阻塞队列。
入队
入队有四个方法,它们分别是add(E e)、offer(E e)、put(E e)、offer(E e, long timeout, TimeUnit unit),它们有什么区别呢?
- add, 添加失败则会抛出异常。
- put, 如果数组满则会阻塞到有空位位置。
- offer,添加失败则会返回false。
public boolean add(E e) {
// 直接调用了父类 abstractQueue中的add方法
return super.add(e);
}
//add 方法会抛出异常,当添加失败的时候就会排除异常。
public boolean add(E e) {
// 调用offer(e)如果成功返回true,如果失败抛出异常
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
public boolean offer(E e) {
// 元素不可为空
checkNotNull(e);
final ReentrantLock lock = this.lock;
// 加锁
lock.lock();
try {
if (count == items.length)
// 如果数组满了就返回false
return false;
else {
// 如果数组没满就调用入队方法并返回true
enqueue(e);
return true;
}
} finally {
// 解锁
lock.unlock();
}
}
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
// 加锁,如果线程中断了抛出异常
lock.lockInterruptibly();
try {
// 如果数组满了,使用notFull等待
// notFull等待的意思是说现在队列满了
// 只有取走一个元素后,队列才不满
// 然后唤醒notFull,然后继续现在的逻辑
// 这里之所以使用while而不是if
// 是因为有可能多个线程阻塞在lock上
// 即使唤醒了可能其它线程先一步修改了队列又变成满的了
// 这时候需要再次等待
while (count == items.length)
notFull.await();
// 入队
enqueue(e);
} finally {
// 解锁
lock.unlock();
}
}
// 这个方法的实现比较简单,直接放入一个可存放的位置,然后对下一个可存放下标++操作,
// 然后与数据容量判断,如果满了则置为0,然后对记录总量进行++操作。然后调用非空锁唤醒操作
//
private void enqueue(E x) {
final Object[] items = this.items;
// 把元素直接放在放指针的位置上
items[putIndex] = x;
// 如果放指针到数组尽头了,就返回头部
if (++putIndex == items.length)
putIndex = 0;
// 数量加1
count++;
// 唤醒notEmpty,因为入队了一个元素,所以肯定不为空了
notEmpty.signal();
}
出队
出队有四个方法,它们分别是remove()、poll()、take()、poll(long timeout, TimeUnit unit),它们有什么区别呢?
-
take方法是阻塞获取,如果为空,则阻塞,直到有对象了再获取,从数组中删除该对象
-
poll方法是如果为空返回null,从数组中删除该对象
-
peek方法是直接返回该对象,并不会从数组中删除
public E remove() {
// 调用poll()方法出队
E x = poll();
if (x != null)
// 如果有元素出队就返回这个元素
return x;
else
// 如果没有元素出队就抛出异常
throw new NoSuchElementException();
}
public E poll() {
final ReentrantLock lock = this.lock;
// 加锁
lock.lock();
try {
// 如果队列没有元素则返回null,否则出队
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
// 加锁
lock.lockInterruptibly();
try {
// 如果队列无元素,则阻塞等待在条件notEmpty上
while (count == 0)
notEmpty.await();
// 有元素了再出队
return 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 {
// 如果队列无元素,则阻塞等待nanos纳秒
// 如果下一次这个线程获得了锁但队列依然无元素且已超时就返回null
while (count == 0) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
return dequeue();
} finally {
lock.unlock();
}
}
private E dequeue() {
final Object[] items = this.items;
@SuppressWarnings("unchecked")
// 取取指针位置的元素
E x = (E) items[takeIndex];
// 把取指针位置设为null
items[takeIndex] = null;
// 取指针前移,如果数组到头了就返回数组前端循环利用
if (++takeIndex == items.length)
takeIndex = 0;
// 元素数量减1
count--;
if (itrs != null)
itrs.elementDequeued();
// 唤醒notFull条件
notFull.signal();
return x;
}
总结
BlockingQueue是所有阻塞队列的顶级接口,它里面定义了一批方法,它们有什么区别呢?
操作 | 抛出异常 | 返回特定值 | 阻塞 | 超时 |
---|---|---|---|---|
入队 | add(e) | offer(e)——false | put(e) | offer(e, timeout, unit) |
出队 | remove() | poll()——null | take() | poll(timeout, unit) |
检查 | element() | peek()——null | - | - |