BlockingQueue:阻塞队列(单项)
BlockingDeque:阻塞队列(双向)
阻塞队列使用:
使用方法和集合大同小异
API:
源码分析
ArrayBlockingQueue:
- 构造方法
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
//初始化一个数组
this.items = new Object[capacity];
//初始化ReentrantLock锁
lock = new ReentrantLock(fair);
//相当于消费者
notEmpty = lock.newCondition();
//相当于生产者
notFull = lock.newCondition();
}
- void put(E e)
// 添加元素到队列(一直阻塞)
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
// lockInterruptibly()是加锁可以被中断的一种机制
lock.lockInterruptibly();
try {
// 如果数组满了,相当于生产者不用在生产了,所以阻塞生产者
while (count == items.length)
notFull.await();
// 添加元素到队列
enqueue(e);
} finally {
lock.unlock();
}
}
- void enqueue(E x)
// 添加元素到队列
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
final Object[] items = this.items;
items[putIndex] = x;
//数组长度是固定的,不需要动态扩容,所以满了之后需要重新开始
if (++putIndex == items.length)
putIndex = 0;
count++;
//添加元素后,相当于生产者生产了产品,需要消费者来消费,所以唤醒消费者
notEmpty.signal();
}
- E take()
// 移除元素
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
// 数组元素为0,相当于没有产品了,所以需要阻塞消费者
notEmpty.await();
// 移除元素
return dequeue();
} finally {
lock.unlock();
}
}
- E dequeue()
// 移除元素
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--;
// itrs是一个迭代器,如果存在的话也需要同步更新
if (itrs != null)
itrs.elementDequeued();
// 消费者消费了产品,所以需要生产者继续生产,所以唤醒生产者
notFull.signal();
return x;
}