隊列
隊列是先進先出(FIFO)的線性表。在具體應用中通常用鏈表或者數組來實現。隊列只允許在后端(稱為rear)進行插入操作,在前端(稱為front)進行刪除操作。隊列的操作方式和堆棧類似,唯一的區別在于隊列只允許新數據在后端進行添加。
操作 | 拋出異常 | 有返回值 |
---|---|---|
Insert | add(e) | offer(e) |
Remove | remove() | poll() |
Examine | element() | peek() |
阻塞隊列
阻塞隊列(BlockingQueue)是一個支持兩個附加操作的隊列,這兩個附加操作支持阻塞的插入和移除方法.
- 支持阻塞的插入方法: 當隊列滿時,隊列會阻塞插入元素的線程,直到隊列不滿為止.
- 支持阻塞的移除方法: 當隊列為空時,獲取元素的線程阻塞等待線程非空.
阻塞隊列通常用于生產者和消費者的場景,生產者就是向隊列里添加元素,而消費者就是從隊列里取出元素. 阻塞隊列就是生產者存儲元素而消費者用來獲取元素的容器.
操作方式 | 拋出異常 | 返回特殊值 | 一直阻塞 | 超時退出 |
---|---|---|---|---|
插入 | add(e) | offer(e) | put(e) | offer(e,time,unit) |
移除 | remove() | poll() | take() | poll(time,unit) |
檢查 | element() | peek() | 不可用 | 不可用 |
注意: 如果是無界阻塞隊列,隊列永遠都不會出現滿的情況,所以使用put或者take方法永遠都不會被阻塞,而且使用put方法時,該方法永遠返回為true.
JDK提供的阻塞隊列
從上面的UML圖可以看到,JKD7提供了7個阻塞隊列:
-
ArrayBlockingQueue
: 由數組結構組成的有界阻塞隊列 -
LinkedBlockingQueue
: 由鏈表結構組成的有界阻塞隊列 -
PriorityBlockingQueue
: 支持優先級排序的無界阻塞隊列 -
DelayQueue
: 使用優先級隊列隊列實現的無界阻塞隊列 -
SynchronousQueue
: 不存儲元素的阻塞隊列 -
LinkedTransferQueue
: 由鏈表結構組成的無界阻塞隊列 -
LinkedBlockingDeque
: 由鏈表結構組成的雙向阻塞隊列
ArrayBlockingQueue
ArrayBlockingQueue
是一個用數組實現的有界隊列,此隊列按照先進先出的原則對元素進行排序.
默認情況下不保證線程公平的訪問隊列,所謂公平訪問隊列是指阻塞的線程,可以按照阻塞的先后順序訪問隊列,即先阻塞線程先訪問隊列.非公平性對先等待的線程是非公平的,當隊列可用時,阻塞的線程都可以爭奪訪問隊列的資格,有可能先阻塞的線程最后才訪問隊列.
為了保證公平性,通常會降低吞吐量,可以使用以下代碼創建一個公平的阻塞隊列.
ArrayBlockingQueue fairQueue= new ArrayBlockingQueue(1000,true);
訪問者的公平性是使用可重入鎖實現的,代碼如下:
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();
}
LinkedBlockingQueue
LinkedBlockingQueue
是一個用鏈表實現的有界阻塞隊列,此隊列默認最大長度為Integer.MAX_VALUE,按照先進先出(FIFO)的原則對元素進行排序
PriorityBlockingQueue
PriorityBlockingQueue
是一個支持優先級的無界阻塞隊列,默認情況下元素采用自然排序升序排列,也可以自定義類實現compareTo()方法來指定元素排序規則,或者初始化PriorityBlockingQueue
時,指定構造參數Comparator來對元素進行排序,需要注意的是不能保證同優先級的元素排序.
DelayQueue
DelayQueue
是一個支持延時獲取元素的無界阻塞隊列,隊列使用PriorityQueue來實現. 隊列中元素必須實現Delayed接口,在創建元素時可以指定多久才能從隊列中獲取當前元素.只有延遲期滿時才能從隊列中提出元素.
DelayQueue
非常有用,可以將DelayQueue
運用在一下場景:
- 緩存系統的設計: 可以送
DelayQueue
保存緩存元素的有效期,使用一個線程循環查詢DelayQueue
,一旦從DelayQueue
獲取元素,就表示緩存到期了. - 定時任務調度:使用
DelayQueue
保存當前將會執行的任務和執行時間,一旦從DelayQueue
中獲取到任務就開始執行,比如TimeQueue就是使用DelayQueue
實現的.
SynchronousQueue
SynchronousQueue
是一個不存儲元素的阻塞隊列,每個put操作必須等待一個take操作,否則不能繼續添加元素.
支持公平訪問隊列,默認情況下線程采用非公平性策略,使用帶boolean參數的構造方法可以實現等待線程采用先進先出(FIFO)的順序訪問隊列.
public SynchronousQueue(boolean fair) {
transferer = fair ? new TransferQueue<E>() : new TransferStack<E>();
}
LinkedTransferQueue
LinkedTransferQueue
是一個由鏈表結構組成的無界阻塞TransferQueue隊列,相當于其他阻塞隊列,LinkedTransferQueue多了一tryTransfer和transfer方法.
-
transfer方法
如果當前有消費者正在等待接收元素(消費者使用take()方法或者帶時間限制的poll方式時)transfer()方法可以吧生產者傳入的元素立即transfer(傳輸)給消費者,如果沒有消費者在等待接收元素,transfer方法將元素存放在隊列的tail節點,并等待該元素被消費者消費了才返回.
-
tryTransfer方法
tryTransfer方法用來試探生產者傳入元素是否能夠直接傳遞給消費者,如果沒有消費者等待接收元素.則返回false, 和transfer方法的區別是tryTransfer方法無論消費者是否接收,方法立即返回,而transfer需要等待消費者消費了才返回.
LinkedBlockingDeque
LinkedBlockingDeque
是一由鏈表結構組成的雙向阻塞隊列,所謂雙向隊列指的是可以從隊列兩端插入和移除元素,雙端隊列因為多了一個操作隊列的入口,在多線程同時入隊時,也就減少了一般競爭.相比其他阻塞隊列,LinkedBlockingDeque
多了addFirst, addLast,offerFirst,offerLast,peekFirst,peekLast等方法.
在初始化LinkedBlockingDeque
時可以設置容量防止其過渡膨脹, 另外,雙向阻塞隊列可以運行在"工作竊取"模式中.
阻塞隊列實現的原理
通知模式實現: 所謂通知模式,就是當生產者從滿的隊列里添加元素時會阻塞生產者,而當消費者消費了一個隊列中的元素后,就會通知生產者當前隊列可用. ArrayBlockingQueue使用ReentrantLock和Condition實現.
/** 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);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
public void put(E e) throws InterruptedException {
Objects.requireNonNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} 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();
}
}
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();
}
/**
* Extracts element at current take position, advances, and signals.
* Call only when holding lock.
*/
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;
}
當往隊列里插入一個元素時,如果隊列不可用,那么阻塞生產者主要通過LockSupport.part(this)實現:
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
然后看看LockSupport的源碼:發現調研setBlocker先保存一下將要阻塞的線程,然后代用unsafe.park阻塞當前線程:
public static void park(Object blocker) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
U.park(false, 0L);
setBlocker(t, null);
}
park是個native方法,會阻塞當前線程,只有以下四種情況中一種發生時,該返回才會返回.
- 與park相對的unpark執行或者已經執行. "已經執行"是指執行unpark,再執行park的情況
- 線程被中斷時
- 等待完time參數指定的毫秒數時
- 異常現象發生時,這個異?,F象沒有任何原因