佇列
目錄
- 佇列
- 阻塞佇列
- 常用方法
- 常用佇列
- 實作原理
阻塞佇列
阻塞佇列(BlockingQueue)是一個支持如下兩個附加操作的佇列,
- A、支持阻塞的插入方法:意思是當佇列滿時,佇列會阻塞插入元素的執行緒,直到佇列不滿
- B、支持阻塞的移除方法:意思是在佇列為空時,獲取元素的執行緒會等待,直到佇列為空
常用方法
| 滿/空時 | 拋出例外 | 回傳特殊值 | 一直阻塞 | 超時退出 |
|---|---|---|---|---|
| 插入方法 | add(e) | offer(e) | put(e) | offer(e,time,unit) |
| 移除方法 | remove() | poll() | take() | poll(time,unit) |
| 檢查方法 | element() | peek() |
常用佇列
? ArrayBlockingQueue:一個由陣列結構組成的有界阻塞佇列,
? LinkedBlockingQueue:一個由鏈表結構組成的有界阻塞佇列,
? PriorityBlockingQueue:一個支持優先級排序的無界阻塞佇列,
? DelayQueue:一個使用優先級佇列實作的無界阻塞佇列,
? SynchronousQueue:一個不存盤元素的阻塞佇列,
? LinkedTransferQueue:一個由鏈表結構組成的無界阻塞佇列,
? LinkedBlockingDeque:一個由鏈表結構組成的雙向阻塞佇列,
實作原理
?
? 使用通知模式實作:就是當生產者往滿的佇列里添加元素時會發生阻塞,然后當消費者消費了佇列中的一個元素后,會通知生產者當前佇列可用,
JDK中ArrayBlockingQueue采用的是Condition來實作的:
// 鎖
final ReentrantLock lock;
//空條件
private final Condition notEmpty;
//滿條件
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 {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
// 若滿,則當前執行緒等待,滿條件進行等待
notFull.await();
// 插入元素,并且通知 不是空的 ,空條件進行釋放
insert(e);
} finally {
lock.unlock();
}
}
// 插入元素
private void insert(E x) {
items[putIndex] = x;
putIndex = inc(putIndex);
++count;
// 通知 當前佇列非空,喚醒notEmpty.await()
notEmpty.signal();
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
// 若空,則當前執行緒等待,空條件進行等待
notEmpty.await();
// 獲取元素,同時通知 未滿,滿條件進行釋放
return extract();
} finally {
lock.unlock();
}
}
// 獲取元素
private E extract() {
final Object[] items = this.items;
E x = this.<E>cast(items[takeIndex]);
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
// 通知 當前佇列未滿,喚醒notFull.await()
notFull.signal();
return x;
}
Java基礎積累
剛開始寫微信公眾號,請多多關注,歡迎,多謝!
微信公眾號:《Java學習積累》
請關注一下,多謝!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/277394.html
標籤:區塊鏈
上一篇:公鑰加密演算法RSA

