概述
自java5后,jdk增加了concurrent包,concurrent中的BlockingQueue,也就是堵塞佇列,BlockingQueue只是一個介面,jdk為其提供了豐富的實作類,適用于不同的場景,這篇講的是ArrayBlockingQueue,
ArrayBlockingQueue簡介
ArrayBlockingQueue繼承了AbstractQueue類和實作了BlockingQueue介面,是一個基于陣列的有界佇列,鎖是基于ReentrantLock實作,只有一個鎖物件,這就導致入隊/出隊共用一把鎖,無法實作存取并行,
應用
1.在實際應用中,設定陣列大小時要充分考慮到資料量,如果設定值過小,容易造成堵塞,而且運行中無法修改大小,
2.不支持null元素,否則報NullPointerException例外,
主要方法

1.插入資料
(1)offer(E e):如果佇列沒滿,回傳true,如果佇列已滿,回傳false(不堵塞),
(2)offer(E e, long timeout, TimeUnit unit):可以設定等待時間,如果佇列已滿,則進行等待,超過等待時間,則回傳false,
(3)put(E e):無回傳值,一直等待,直至佇列空出位置,
2.獲取資料
(1)poll():如果有資料,出隊,如果沒有資料,回傳null,
(2)poll(long timeout, TimeUnit unit):可以設定等待時間,如果沒有資料,則等待,超過等待時間,則回傳null,
(3)take():如果有資料,出隊,如果沒有資料,一直等待(堵塞),
原始碼分析
1.AbstractQueue
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable
繼承了AbstractQueue抽象類,實作了BlockingQueue介面,
2.成員變數
final Object[] items;//佇列
/** 下次出隊下標(take、poll、remove) */
int takeIndex;
/** 下次入隊下標(pull、offer、add) */
int putIndex;
/** 佇列中元素個數 */
int count;
/** 鎖 */
final ReentrantLock lock;
/** 等待條件(出隊) */
private final Condition notEmpty;
/** 等待條件(入隊) */
private final Condition notFull;
/**
* 迭代器
*/
transient Itrs itrs = null;
ArrayBlockingQueue是基于陣列的佇列,鎖是基于ReentrantLock,
3.建構式
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
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();
}
實體化ArrayBlockingQueue必須要設定陣列長度,這就是為什么ArrayBlockingQueue是一個有界佇列
4.offer
public boolean offer(E e) {
//判斷你是否為null,為null拋NullPointerException
checkNotNull(e);
//獲取鎖
final ReentrantLock lock = this.lock;
lock.lock();
try {
//如果佇列已滿,回傳false
if (count == items.length)
return false;
else {
//入隊,回傳true
enqueue(e);
return true;
}
} finally {
//釋放鎖
lock.unlock();
}
}
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
//判斷是否為null,為null拋NullPointerException
checkNotNull(e);
long nanos = unit.toNanos(timeout);
//獲取鎖
final ReentrantLock lock = this.lock;
//lockInterruptibly優先考慮回應中斷
lock.lockInterruptibly();
try {
//如果佇列已滿
while (count == items.length) {
//超時直接回傳false
if (nanos <= 0)
return false;
//生產執行緒堵塞nanos時間,也有可能被喚醒,如果超過nanos時間還未被喚醒,則nanos=0,再次回圈,就會回傳false
nanos = notFull.awaitNanos(nanos);
}
//設定元素
enqueue(e);
return true;
} finally {
//釋放鎖
lock.unlock();
}
}
private void enqueue(E x) {
// assert lock.getHoldCount() == 1;
// assert items[putIndex] == null;
//獲取陣列
final Object[] items = this.items;
//向入隊下標陣列設定元素
items[putIndex] = x;
//如果入隊下標已經是最后一個,則證明佇列已滿,入隊下標設定為0
if (++putIndex == items.length)
putIndex = 0;
count++;
//喚醒堵塞的消費執行緒
notEmpty.signal();
}
為什么offer方法設定null會拋錯,因為第一句代碼就是checkNotNull方法,佇列已滿回傳false,佇列未滿入隊,回傳true,
兩個offer方法的區別在于是否有等待時間,實作上基本一致,
5.put
public void put(E e) throws InterruptedException {
//判斷是否為null,為null拋NullPointerException
checkNotNull(e);
//獲取鎖
final ReentrantLock lock = this.lock;
//lockInterruptibly優先考慮回應中斷
lock.lockInterruptibly();
try {
//如果佇列已滿
while (count == items.length)
//一直堵塞,直至被喚醒
notFull.await();
//設定元素
enqueue(e);
} finally {
//釋放鎖
lock.unlock();
}
}
put和offer方法差別基本不大,只是put方法通過 notFull.await(),一直堵塞,直至被喚醒
6.poll
public E poll() {
//獲取鎖
final ReentrantLock lock = this.lock;
lock.lock();
try {
//如果佇列為空,回傳null,否則回傳dequeue方法獲取的值
return (count == 0) ? null : dequeue();
} finally {
//釋放鎖
lock.unlock();
}
}
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
//獲取等待時間
long nanos = unit.toNanos(timeout);
//獲取鎖
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
//如果佇列為空
while (count == 0) {
//當超時后,直接回傳null
if (nanos <= 0)
return null;
//將執行緒堵塞nanos時間,堵塞時間內可能被喚醒,超過nanos時間,nanos=0,下次回圈回傳null
nanos = notEmpty.awaitNanos(nanos);
}
//獲取元素
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;
//如果出隊是陣列中最后一個,下一個出隊從0開始
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
//喚醒生產的執行緒
notFull.signal();
return x;
}
poll方法為什么獲取不到資料會回傳null了,兩個poll之間的區別在于是否有堵塞時間,其他基本一致
7.take
public E take() throws InterruptedException {
//獲取鎖
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
//如果佇列為空,則堵塞,直至被喚醒
while (count == 0)
notEmpty.await();
//獲取元素
return dequeue();
} finally {
//釋放鎖
lock.unlock();
}
}
從原始碼可以看出,take十分簡單,核心邏輯是佇列為空,一致等待,直至被喚醒,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/197266.html
標籤:java
上一篇:JAVA練習題二
