[java隊列]——ArrayBlockingQueue
隊列
隊列就是一種先進先出(FIFO)的線性表
ArrayBlockingQueue簡介
- 數組實現
- 線程安全
- 不需要擴容,數組大小固定
- 位於java併發包下
ArrayBlockingQueue內部實現
基本屬性
package java.util.concurrent;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.ref.WeakReference;
import java.util.Spliterators;
import java.util.Spliterator;
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
private static final long serialVersionUID = -817911632652898426L;
//存儲隊列元素的數組
final Object[] items;
//記錄每次待取元素的位置指針
int takeIndex;
//記錄每次待存元素的位置指針
int putIndex;
//隊列元素個數
int count;
//可重入鎖,對以下兩個Condition的併發控制
final ReentrantLock lock;
//非空條件
private final Condition notEmpty;
//非滿條件
private final Condition notFull;
結論:
- 通過存、取指針來記錄下一次要操作的位置
- 用數組存儲元素
- 利用可重入鎖來對兩個Condition做併發控制
構造方法
//只傳入隊列容量
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();
}
//傳入容量、是否使用公平鎖,以及要存入的集合元素
public ArrayBlockingQueue(int capacity, boolean fair,
Collection<? extends E> c) {
this(capacity, fair);
final ReentrantLock lock = this.lock;
lock.lock(); // Lock only for visibility, not mutual exclusion
try {
int i = 0;
try {
for (E e : c) {
checkNotNull(e);
items[i++] = e;
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new IllegalArgumentException();
}
count = i;
putIndex = (i == capacity) ? 0 : i;
} finally {
lock.unlock();
}
}
結論:
- 可通過構造方法選擇可重入鎖是否使用公平鎖
- 可通過構造方法設置隊列的容量
入隊
入隊提供的方法
add(E e)方法
//ArrayBlockingQueue的add方法
public boolean add(E e) {
return super.add(e);
}
//父類中的add方法 super.add(e) 如下
public boolean add(E e) {
//調用子類(ArrayBlockingQueue)的offer方法
if (offer(e))
return true;
else
//可以看到add方法,如果入隊失敗是會拋異常的
throw new IllegalStateException("Queue full");
}
offer(E e)方法
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();
}
}
put(E e)方法
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
//加鎖,如果被中斷拋出InterruptedException異常
lock.lockInterruptibly();
try {
while (count == items.length)
//如果隊列滿了。則等待notFull(非滿)條件,阻塞直到隊列爲非滿才返回
notFull.await();
//真正的入隊方法
enqueue(e);
} finally {
lock.unlock();
}
}
offer(E e, long timeout, TimeUnit unit)
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
checkNotNull(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length) {
if (nanos <= 0)
//如果時間到了,仍然後沒有空間,直接返回false
return false;
//阻塞等待nanos時間後返回
nanos = notFull.awaitNanos(nanos);
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}
真正的入隊——enqueue(E x)方法
private void enqueue(E x) {
final Object[] items = this.items;
items[putIndex] = x;
if (++putIndex == items.length)
//當存指針達到數組末尾時,指針位置重新設置爲0
//從這裏可以看出是使用循環數組
putIndex = 0;
count++;
//存完元素後,發出數組內元素非空信號
notEmpty.signal();
}
結論:
- add方法其實是調用offer方法,如果隊列滿了入隊失敗拋異常,不阻塞
- offer方法入隊成功返回true,隊列滿了入隊返回false,不阻塞
- offer timeout方法,阻塞一段時間後,若隊列仍滿,無法入隊則返回fasles
- put方法,若隊列滿,一直阻塞,直到隊列非滿入隊才返回true,或者線程被中斷才拋出中斷異常
出隊
與入隊類似,出隊也有四個方法remove()、poll()、take()、poll(long timeout, TimeUnit unit),由於實現方式與入隊非常類似,這裏直接貼源碼不做註釋,大家可以自己研讀一下。非常易讀
//這個方法在ArrayBlcokingQueue的父類AbstractQueue中
public E remove() {
E x = poll();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return 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) {
if (nanos <= 0)
return 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;
if (++takeIndex == items.length)
takeIndex = 0;
count--;
if (itrs != null)
itrs.elementDequeued();
notFull.signal();
return x;
}
結論:
- remove方法,如果隊列爲空出隊失敗則拋出異常
- poll方法,如果隊列爲空出隊失敗則返回false
- poll timeout方法,阻塞一段時間,如果隊列仍然爲空,則返回false
- take方法,如果隊列爲空,一直阻塞,直到隊列不爲空才返回,或者線程被中斷才拋出中斷異常
ArrayBlockingQueue總結
實現:
- 數組實現
- 線程安全,利用可重入鎖控制非空和非滿兩個Condition進行併發控制
- 不需要擴容,數組大小固定,利用循環數組
缺點: - 隊列長度在初始化時指定,並且不會自動擴容,選擇容量時需謹慎
- 若隊列長期爲空或者爲滿,會導致對應的取、存線程一直處於阻塞,阻塞線程會越變越多
- 只使用一個鎖來控制,併發效率低
BlockingQueue接口
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable
可以看到ArrayBlockingQueue實現了BlockingQueue接口,那麼BlockingQueue接口定義了哪些方法呢。
下面分析一下其中的一些方法和區別
隊列操作 | 正常返回特定值 | 可能拋出異常 | 阻塞超時返回 | 長期阻塞 |
---|---|---|---|---|
入隊 | add | offer | put | offer(e,timeoute,unit) |
出隊 | remove | poll | take | poll(timeout,unit) |
檢查 | element | peek | —— | —— |