ArrayBlockingQueue:定常的阻塞队列,当多个线程对队列进行操作的时候可以满足线程安全,主要是通过ReentrantLock(同步队列)、Condition(条件阻塞队列来实现)。
1、构造方法
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(); // 创建条件阻塞队列(当队列不是满的时候唤醒条件)
}
2、入队方法
add:add(),底层调用offer方法,入队成功返回true,如果入队失败则抛出异常。
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
offer:offer,添加一个元素到队列,如果添加成功返回true,添加失败返回false。
public boolean offer(E e) {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count == items.length)
return false;
else {
enqueue(e);
return true;
}
} finally {
lock.unlock();
}
}