首先分析一下为什么写要加锁
以offer方法为例(增加元素)
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
/** 存元素的数组 */
final Object[] items;
/** 删除,查询元素时,使用的下标 */
int takeIndex;
/** 添加元素时,使用的下标 */
int putIndex;
/** 元素总数 */
int count;
/** 锁 */
final ReentrantLock lock;
// 加元素的方法
public boolean offer(E e) {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lock(); //加锁
try {
if (count == items.length)
return false;
else {
enqueue(e); //核心是调用enqueue方法
return true;
}
} finally {
lock.unlock(); //解锁
}
}
/**
这个方法就是关键,里面有一行代码让putIndex自增
这个操作不是原子的,为了防止出现两个线程++,结果仅仅加1的现象
需要加锁
**/
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();
}
}
再来分析一下为什么读也要加锁
主要就是跟删除操作有关,我们来看一下删除操作&查询队首的源码
具体分析在注释中
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
//前面的不写了
// 删元素的方法
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : dequeue(); //核心是调用dequeue方法
} finally {
lock.unlock();
}
}
// 删除分为2步
// 步骤1.删除takeIndex指向的元素
// 步骤2.takeIndex指向后一个
// 明白了这2步,就明白为什么查询队首的peek方法也需要加锁
// 因为如果不加锁,万一在步骤1,2中间,别人来peek,就会拿到null
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; //步骤1
if (++takeIndex == items.length) //步骤2
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
//
public E peek() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return itemAt(takeIndex); // null when queue is empty
} finally {
lock.unlock();
}
}
}