java+arrayblockquene_Java源码分析-ArrayBlockingQueue
ArrayBlockingQueue是JDK1.5開始concurrent包中提供的并發工具類,是一個基于數組的有界的先進先出隊列,如果加入元素時,數組已滿,或數組為空時,取元素都會阻塞當前線程,是一個典型的生產者消費者模式。類似的類還有LinkedBlockingQueue,PriorityBlockingQueue。
繼承關系
public class ArrayBlockingQueue extends AbstractQueue
implements BlockingQueue, java.io.Serializable
public interface BlockingQueue extends Queue
核心成員變量
final Object[] items; //保存元素
/** items index for next take, poll, peek or remove */
int takeIndex; //指向隊頭
/** items index for next put, offer, or add */
int putIndex; //指向隊尾
/** Number of elements in the queue */
int count; //隊中元素計數
/*
* Concurrency control uses the classic two-condition algorithm
* found in any textbook.
*/
/** Main lock guarding all access */
final ReentrantLock lock; //可重入鎖
/** Condition for waiting takes */
private final Condition notEmpty; //條件變量
/** Condition for waiting puts */
private final Condition notFull; //條件變量
構造方法
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity]; //初始化指定大小的有界隊列
lock = new ReentrantLock(fair); //fair指示該鎖是否是公平的
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
添加元素:put方法
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await(); //添加元素時,如果已滿,則阻塞當前線程,等待在notFull這個條件變量上,等待notFull調用signal喚醒
enqueue(e); //此時隊列肯定未滿
} finally {
lock.unlock();
}
}
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加1,如果到達數組尾部,則從0開始
putIndex = 0;
count++; //增加計數
notEmpty.signal(); //增加一個元素后,如果有線程等待在noEmpty條件變量上,通知并喚醒一種一個線程。
}
put方法首先判斷隊列是否已滿,如果已滿,則阻塞當前線程,等待在notFull這個條件變量上,等待notFull調用signal喚醒。當隊列非空時,將該元素加入隊尾,增加元素計數,喚醒因為進行去操作時數組為空而等待在notEmpty上的線程,通知它此時隊列已經有元素了,你可以進行取操作了。
取元素:take方法
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await(); //取元素但是隊列為空時,阻塞線程,等待在notEmpty上
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--; //計數減1
if (itrs != null)
itrs.elementDequeued();
notFull.signal(); //通知因為添加元素但是隊列已滿時而阻塞的線程,隊列此時可插入了
return x; //返回隊頭元素
}
take方法和put方法類似,先檢查隊列是否為空,隊列為空時,阻塞線程,等待在notEmpty上。當隊列非空時,進行出隊操作。同時還要通知因為添加元素但是隊列已滿時而阻塞的線程,隊列此時可插入了。
總結
以上是生活随笔為你收集整理的java+arrayblockquene_Java源码分析-ArrayBlockingQueue的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 扫雷命令,Matlab版扫
- 下一篇: php 中curd表达啥,thinkph