相關文章:
JAVA多線程創建、使用看這一篇就夠了
Java多線程進階實戰
文章目錄
一.ArrayBlockingQueue 介紹
ArrayBlockingQueue是一個阻塞式的隊列,繼承自AbstractBlockingQueue,實現了BlockingQueue接口。
底層以數組的形式保存數據(Object [])。常用的操作包括 add,offer,put,remove,poll,take,peek。
public class ArrayBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {}
根據 ArrayBlockingQueue 的名字我們都可以看出,它是一個隊列,並且是一個基於數組的阻塞隊列。
ArrayBlockingQueue 是一個有界隊列,有界也就意味着,它不能夠存儲無限多數量的對象。
所以在創建 ArrayBlockingQueue 時,必須要給它指定一個隊列的大小。
二、創建ArrayBlockingQueue
ArrayBlockingQueue 爲我們提供了三種創建方式:
2.1 默認非公平阻塞隊列
示例:
ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(10);
源碼:
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
這裏內部調用了公平鎖方法,只是默認未開啓
2.2 公平阻塞隊列
示例:
ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(10,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();
}
2.3 給定集合的元素,按集合迭代器的遍歷順序添加
這個看你參數的傳達是公平還是非公平,內部是for循環添加,也進行加鎖處理
示例:
ArrayBlockingQueue<String> blockingQueue2 = new ArrayBlockingQueue<String>(10, true, new ArrayList<>());
源碼:
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();
}
}
三、使用ArrayBlockingQueue
3.1 添加
這裏添加也爲我們提供了三種方式,我們一一說來;
3.1.1 offer()方法
示例 :
blockingQueue.offer("Java有貨");
源碼:
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();
}
}
解析: 首先會對我們的參數進行非空檢驗,之後獲取全局鎖,獲取之後判斷是否達到最大長度,到達返回false,否則進行新增,成功返回true
3.1.2 add()方法
示例 :
blockingQueue.add("Java有貨");
源碼:
public boolean add(E e) {
return super.add(e);
}
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
解析: 這裏也會調用offer(),不同之處在於,**add()**方法添加失敗,會報錯,不是很友好
3.1.3 put()方法
示例 :
try {
blockingQueue.put("Java有貨");
} catch (InterruptedException e) {
e.printStackTrace();
}
源碼:
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
解析:大家可以看出,調用**put()**方法他調用了 notFull.await();,也就是說,當隊列,長多到達最大值時,在進行新增操作,會使對了阻塞,直到條件不滿足時在新增,否則一直阻塞;
3.1.4 總結
根據以上幾種方式的介紹,與使用,**add()**方法會直接報錯,put()方法如果一直阻塞,對服務器的性能消耗太大,所以個人覺得使用offer() 方法更加有利於系統的性能,畢竟失敗我們也知道,可以做後續的處理
3.2 刪除
3.2.1 remove()
示例:
blockingQueue.remove("Java有貨");
源碼:
public boolean remove(Object o) {
if (o == null) return false;
final Object[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count > 0) {
final int putIndex = this.putIndex;
int i = takeIndex;
do {
if (o.equals(items[i])) {
removeAt(i);
return true;
}
if (++i == items.length)
i = 0;
} while (i != putIndex);
}
return false;
} finally {
lock.unlock();
}
}
解析:首先判斷我們的元素是否爲null,不爲null,則通過final Object[] items = this.items;獲取當前對列,然後進行 do while 循環操作,進行刪除,成功爲true,否則爲false
3.2.2 poll()
獲取對列的首個元素
示例:
blockingQueue.poll("Java有貨");
源碼:
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : 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;
}
解析:這裏主要dequeue()方法,如果獲取的對列無元素,直接返回null,否則就是獲取對列的第一個元素,賦值給E 然後將獲取後的下標元素重置爲null,之後就是下標,長度的加減操作
3.2.3 take()
獲取對列的首個元素
示例:
try {
blockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
源碼:
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
解析:這裏不多做解釋,和之前的新增類
3.3 檢查方法
3.3.1 element()
獲取但不移除此隊列的頭元素,沒有元素則拋異常
3.3.2 peek()
獲取但不移除此隊列的頭;若隊列爲空,則返回 null。
這裏也不多說,和之前的都差不多
擴展
下面這段代碼大家應該也很熟悉,判斷是否包含,內容和之前解說的差不多,也是獲取元素,進行循環判定,
public boolean contains(Object o) {
if (o == null) return false;
final Object[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count > 0) {
final int putIndex = this.putIndex;
int i = takeIndex;
do {
if (o.equals(items[i]))
return true;
if (++i == items.length)
i = 0;
} while (i != putIndex);
}
return false;
} finally {
lock.unlock();
}
}
今天的分享就到這裏,希望對大家有所幫助
關注 Java有貨領取更多資料
聯繫小編。微信:372787553,帶您進羣互相學習
左側小編微信,右側獲取免費資料
技術博客:https://blog.csdn.net/weixin_38937840
SpringCloud學習代碼: https://github.com/Dylan-haiji/javayh-cloud
Redis、Mongo、Rabbitmq、Kafka學習代碼: https://github.com/Dylan-haiji/javayh-middleware
AlibabaCloud學習代碼:https://github.com/Dylan-haiji/javayh-cloud-nacos
SpringBoot+SpringSecurity實現自定義登錄學習代碼:https://github.com/Dylan-haiji/javayh-distribution