ArrayBlockingQueue的简要介绍
ArrayBlockingQueue是基于数组实现的一个有界的阻塞队列,一旦进行初始化操作,阻塞队列的大小将会被固定,不能进行修改。底层使用数组进行实现。提供FIFO的功能。队列头上的元素是在队列中呆了最长时间的元素,队列尾上的元素是在队列中呆了时间最短的元素。新元素会插入在队列尾部,从队列获取元素时会从队列头上获取。
当队列满的时候在向队列进行添加数据的时候,会进行阻塞。当队列为空的时候,进行消费的时候,也会进行阻塞的。这个类为消费者和生产者提供公平锁和非公平锁的操作。
ArrayBlockingQueue的主要方法和实现机制
- 构造函数
/***
* 只包含大小的构造函数
* @param capacity 数组大小
**/
public ArrayBlockingQueue(int capacity) {
//不传是否公平的时候 默认是非公平锁
this(capacity, false);
}
/***
* 构造函数
* @param capacity 数组的大小
* @param fair 是否使用公平锁
**/
public ArrayBlockingQueue(int capacity, boolean fair) {
//传入的数组大小小于0的时候进行抛出异常
if (capacity <= 0)
throw new IllegalArgumentException();
//进行数组的创建
this.items = new Object[capacity];
//进行创建公平锁/非公平锁
lock = new ReentrantLock(fair);
//Condition for waiting take
notEmpty = lock.newCondition();
//Condition for waiting puts
notFull = lock.newCondition();
}
/***
* 在进行初始化的时候 将数组默认添加到ArrayBlockingQueue中去
*@param capacity 数组的大小
*@param fair 是否使用公平锁
*@param c 集合数据
****/
public ArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair);//进行调用初始化的方法
/**开始进行遍历集合,并且进行添加的操作**/
//进行获取锁的操作
final ReentrantLock lock = this.lock;
lock.lock(); // Lock only for visibility, not mutual exclusion
try {
int i = 0;
try {
//进行添加的时候可能会出现数组越界的问题在这里进行捕获
for (E e : c) {
checkNotNull(e);
items[i++] = e;
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new IllegalArgumentException();
}
count = i;//当前队列里面的数量
putIndex = (i == capacity) ? 0 : i;//下一个位置的坐标
} finally {
lock.unlock();
}
}
- 添加的方法
/**
*@param e 进行添加的元素
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void put(E e) throws InterruptedException {
//检查元素是否是null 是null的话抛出空指针异常
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
//进行判断当前队列的数量 和数组的长度是否相等 相等进行等待 不相等进行添加的操作
while (count == items.length)
notFull.await();
//向队列中进行添加元素
enqueue(e);
} finally {
lock.unlock();
}
}
/**
*进行元素的添加并且进行唤醒消费方,让消费方进行消费
*
*/
private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0;
count++;//长度进行++
notEmpty.signal();//进行唤醒消费方
}
取数据的方法
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;
}