激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - Java 并發編程ArrayBlockingQueue的實現

Java 并發編程ArrayBlockingQueue的實現

2021-08-09 11:49maomaoJava Java教程

這篇文章主要介紹了Java 并發編程ArrayBlockingQueue的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

一、簡介

ArrayBlockingQueue 顧名思義:基于數組的阻塞隊列。數組是要指定長度的,所以使用 ArrayBlockingQueue 時必須指定長度,也就是它是一個有界隊列。它實現了 BlockingQueue 接口,有著隊列、集合以及阻塞隊列的所有方法。

Java 并發編程ArrayBlockingQueue的實現

ArrayBlockingQueue 是線程安全的,內部使用 ReentrantLock 來保證。ArrayBlockingQueue 支持對生產者線程和消費者線程進行公平的調度。當然默認情況下是不保證公平性的,因為公平性通常會降低吞吐量,但是可以減少可變性和避免線程饑餓問題。

二、數據結構

通常,隊列的實現方式有數組和鏈表兩種方式。對于數組這種實現方式來說,我們可以通過維護一個隊尾指針,使得在入隊的時候可以在 O(1)O(1) 的時間內完成;但是對于出隊操作,在刪除隊頭元素之后,必須將數組中的所有元素都往前移動一個位置,這個操作的復雜度達到了 O(n)O(n),效果并不是很好。如下圖所示:

Java 并發編程ArrayBlockingQueue的實現

為了解決這個問題,我們可以使用另外一種邏輯結構來處理數組中各個位置之間的關系。假設現在我們有一個數組 A[1…n],我們可以把它想象成一個環型結構,即 A[n] 之后是 A[1],相信了解過一致性 Hash 算法的童鞋應該很容易能夠理解。

如下圖所示:我們可以使用兩個指針,分別維護隊頭和隊尾兩個位置,使入隊和出隊操作都可以在 O(1O(1 )的時間內完成。當然,這個環形結構只是邏輯上的結構,實際的物理結構還是一個普通的數組。

Java 并發編程ArrayBlockingQueue的實現

講完 ArrayBlockingQueue 的數據結構,接下來我們從源碼層面看看它是如何實現阻塞的。

三、源碼分析

3.1 屬性

  1. // 隊列的底層結構
  2. final Object[] items;
  3. // 隊頭指針
  4. int takeIndex;
  5. // 隊尾指針
  6. int putIndex;
  7. // 隊列中的元素個數
  8. int count;
  9.  
  10. final ReentrantLock lock;
  11.  
  12. // 并發時的兩種狀態
  13. private final Condition notEmpty;
  14. private final Condition notFull;

items 是一個數組,用來存放入隊的數據;count 表示隊列中元素的個數;takeIndex 和 putIndex 分別代表隊頭和隊尾指針。

3.2 構造方法

  1. public ArrayBlockingQueue(int capacity) {
  2. this(capacity, false);
  3. }
  4.  
  5. public ArrayBlockingQueue(int capacity, boolean fair) {
  6. if (capacity <= 0)
  7. throw new IllegalArgumentException();
  8. this.items = new Object[capacity];
  9. lock = new ReentrantLock(fair);
  10. notEmpty = lock.newCondition();
  11. notFull = lock.newCondition();
  12. }
  13.  
  14. public ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c) {
  15. this(capacity, fair);
  16.  
  17. final ReentrantLock lock = this.lock;
  18. lock.lock(); // Lock only for visibility, not mutual exclusion
  19. try {
  20. int i = 0;
  21. try {
  22. for (E e : c) {
  23. checkNotNull(e);
  24. items[i++] = e;
  25. }
  26. } catch (ArrayIndexOutOfBoundsException ex) {
  27. throw new IllegalArgumentException();
  28. }
  29. count = i;
  30. putIndex = (i == capacity) ? 0 : i;
  31. } finally {
  32. lock.unlock();
  33. }
  34. }

第一個構造函數只需要指定隊列大小,默認為非公平鎖;第二個構造函數可以手動指定公平性和隊列大小;第三個構造函數里面使用了 ReentrantLock 來加鎖,然后把傳入的集合元素按順序一個個放入 items 中。這里加鎖目的不是使用它的互斥性,而是讓 items 中的元素對其他線程可見(參考 AQS 里的 state 的 volatile 可見性)。

3.3 方法

3.3.1 入隊

ArrayBlockingQueue 提供了多種入隊操作的實現來滿足不同情況下的需求,入隊操作有如下幾種:

  • boolean add(E e)
  • void put(E e)
  • boolean offer(E e)
  • boolean offer(E e, long timeout, TimeUnit unit)

(1)add(E e)

  1. public boolean add(E e) {
  2. return super.add(e);
  3. }
  4.  
  5. //super.add(e)
  6. public boolean add(E e) {
  7. if (offer(e))
  8. return true;
  9. else
  10. throw new IllegalStateException("Queue full");
  11. }

可以看到 add 方法調用的是父類,也就是 AbstractQueue 的 add 方法,它實際上調用的就是 offer 方法。

(2)offer(E e)

我們接著上面的 add 方法來看 offer 方法:

  1. public boolean offer(E e) {
  2. checkNotNull(e);
  3. final ReentrantLock lock = this.lock;
  4. lock.lock();
  5. try {
  6. if (count == items.length)
  7. return false;
  8. else {
  9. enqueue(e);
  10. return true;
  11. }
  12. } finally {
  13. lock.unlock();
  14. }
  15. }

offer 方法在隊列滿了的時候返回 false,否則調用 enqueue 方法插入元素,并返回 true。

  1. private void enqueue(E x) {
  2. final Object[] items = this.items;
  3. items[putIndex] = x;
  4. // 圓環的index操作
  5. if (++putIndex == items.length)
  6. putIndex = 0;
  7. count++;
  8. notEmpty.signal();
  9. }

enqueue 方法首先把元素放在 items 的 putIndex 位置,接著判斷在 putIndex+1 等于隊列的長度時把 putIndex 設置為0,也就是上面提到的圓環的 index 操作。最后喚醒等待獲取元素的線程。

(3)offer(E e, long timeout, TimeUnit unit)

該方法在 offer(E e) 的基礎上增加了超時的概念。

  1. public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
  2.  
  3. checkNotNull(e);
  4. // 把超時時間轉換成納秒
  5. long nanos = unit.toNanos(timeout);
  6. final ReentrantLock lock = this.lock;
  7. // 獲取一個可中斷的互斥鎖
  8. lock.lockInterruptibly();
  9. try {
  10. // while循環的目的是防止在中斷后沒有到達傳入的timeout時間,繼續重試
  11. while (count == items.length) {
  12. if (nanos <= 0)
  13. return false;
  14. // 等待nanos納秒,返回剩余的等待時間(可被中斷)
  15. nanos = notFull.awaitNanos(nanos);
  16. }
  17. enqueue(e);
  18. return true;
  19. } finally {
  20. lock.unlock();
  21. }
  22. }

利用了 Condition 的 awaitNanos 方法,等待指定時間,因為該方法可中斷,所以這里利用 while 循環來處理中斷后還有剩余時間的問題,等待時間到了以后調用 enqueue 方法放入隊列。

(4)put(E e)

  1. public void put(E e) throws InterruptedException {
  2. checkNotNull(e);
  3. final ReentrantLock lock = this.lock;
  4. lock.lockInterruptibly();
  5. try {
  6. while (count == items.length)
  7. notFull.await();
  8. enqueue(e);
  9. } finally {
  10. lock.unlock();
  11. }
  12. }

put 方法在 count 等于 items 長度時,一直等待,直到被其他線程喚醒。喚醒后調用 enqueue 方法放入隊列。

3.3.2 出隊

入隊列的方法說完后,我們來說說出隊列的方法。ArrayBlockingQueue 提供了多種出隊操作的實現來滿足不同情況下的需求,如下:

  • E poll()
  • E poll(long timeout, TimeUnit unit)
  • E take()
  • drainTo(Collection<? super E> c, int maxElements)

(1)poll()

  1. public E poll() {
  2. final ReentrantLock lock = this.lock;
  3. lock.lock();
  4. try {
  5. return (count == 0) ? null : dequeue();
  6. } finally {
  7. lock.unlock();
  8. }
  9. }

poll 方法是非阻塞方法,如果隊列沒有元素返回 null,否則調用 dequeue 把隊首的元素出隊列。

  1. private E dequeue() {
  2. final Object[] items = this.items;
  3. @SuppressWarnings("unchecked")
  4. E x = (E) items[takeIndex];
  5. items[takeIndex] = null;
  6. if (++takeIndex == items.length)
  7. takeIndex = 0;
  8. count--;
  9. if (itrs != null)
  10. itrs.elementDequeued();
  11. notFull.signal();
  12. return x;
  13. }

dequeue 會根據 takeIndex 獲取到該位置的元素,并把該位置置為 null,接著利用圓環原理,在 takeIndex 到達列表長度時設置為0,最后喚醒等待元素放入隊列的線程。

(2)poll(long timeout, TimeUnit unit)

該方法是 poll() 的可配置超時等待方法,和上面的 offer 一樣,使用 while 循環配合 Condition 的 awaitNanos 來進行等待,等待時間到后執行 dequeue 獲取元素。

  1. public E poll(long timeout, TimeUnit unit) throws InterruptedException {
  2. long nanos = unit.toNanos(timeout);
  3. final ReentrantLock lock = this.lock;
  4. lock.lockInterruptibly();
  5. try {
  6. while (count == 0) {
  7. if (nanos <= 0)
  8. return null;
  9. nanos = notEmpty.awaitNanos(nanos);
  10. }
  11. return dequeue();
  12. } finally {
  13. lock.unlock();
  14. }
  15. }

(3)take()

  1. public E take() throws InterruptedException {
  2. final ReentrantLock lock = this.lock;
  3. lock.lockInterruptibly();
  4. try {
  5. while (count == 0)
  6. notEmpty.await();
  7. return dequeue();
  8. } finally {
  9. lock.unlock();
  10. }
  11. }

取走隊列里排在首位的對象,不同于 poll() 方法,若BlockingQueue為空,就阻塞等待直到有新的數據被加入。
(4)drainTo()

  1. public int drainTo(Collection<? super E> c) {
  2. return drainTo(c, Integer.MAX_VALUE);
  3. }
  4.  
  5. public int drainTo(Collection<? super E> c, int maxElements) {
  6. checkNotNull(c);
  7. if (c == this)
  8. throw new IllegalArgumentException();
  9. if (maxElements <= 0)
  10. return 0;
  11. final Object[] items = this.items;
  12. final ReentrantLock lock = this.lock;
  13. lock.lock();
  14. try {
  15. int n = Math.min(maxElements, count);
  16. int take = takeIndex;
  17. int i = 0;
  18. try {
  19. while (i < n) {
  20. @SuppressWarnings("unchecked")
  21. E x = (E) items[take];
  22. c.add(x);
  23. items[take] = null;
  24. if (++take == items.length)
  25. take = 0;
  26. i++;
  27. }
  28. return n;
  29. } finally {
  30. // Restore invariants even if c.add() threw
  31. if (i > 0) {
  32. count -= i;
  33. takeIndex = take;
  34. if (itrs != null) {
  35. if (count == 0)
  36. itrs.queueIsEmpty();
  37. else if (i > take)
  38. itrs.takeIndexWrapped();
  39. }
  40. for (; i > 0 && lock.hasWaiters(notFull); i--)
  41. notFull.signal();
  42. }
  43. }
  44. } finally {
  45. lock.unlock();
  46. }
  47. }

drainTo 相比于其他獲取方法,能夠一次性從隊列中獲取所有可用的數據對象(還可以指定獲取數據的個數)。通過該方法,可以提升獲取數據效率,不需要多次分批加鎖或釋放鎖。

3.3.3 獲取元素

  1. public E peek() {
  2. final ReentrantLock lock = this.lock;
  3. lock.lock();
  4. try {
  5. return itemAt(takeIndex); // null when queue is empty
  6. } finally {
  7. lock.unlock();
  8. }
  9. }
  10.  
  11. final E itemAt(int i) {
  12. return (E) items[i];
  13. }

這里獲取元素時上鎖是為了避免臟數據的產生。

3.3.4 刪除元素

我們可以想象一下,隊列中刪除某一個元素時,是不是要遍歷整個數據找到該元素,并把該元素后的所有元素往前移一位,也就是說,該方法的時間復雜度為 O(n)O(n)。

  1. public boolean remove(Object o) {
  2. if (o == null) return false;
  3. final Object[] items = this.items;
  4. final ReentrantLock lock = this.lock;
  5. lock.lock();
  6. try {
  7. if (count > 0) {
  8. final int putIndex = this.putIndex;
  9. int i = takeIndex;
  10. // 從takeIndex一直遍歷到putIndex,直到找到和元素o相同的元素,調用removeAt進行刪除
  11. do {
  12. if (o.equals(items[i])) {
  13. removeAt(i);
  14. return true;
  15. }
  16. if (++i == items.length)
  17. i = 0;
  18. } while (i != putIndex);
  19. }
  20. return false;
  21. } finally {
  22. lock.unlock();
  23. }
  24. }

remove 方法比較簡單,它從 takeIndex 一直遍歷到 putIndex,直到找到和元素 o 相同的元素,調用 removeAt 進行刪除。我們重點來看一下 removeAt 方法。

  1. void removeAt(final int removeIndex) {
  2. final Object[] items = this.items;
  3. if (removeIndex == takeIndex) {
  4. // removing front item; just advance
  5. items[takeIndex] = null;
  6. if (++takeIndex == items.length)
  7. takeIndex = 0;
  8. count--;
  9. if (itrs != null)
  10. itrs.elementDequeued();
  11. } else {
  12. // an "interior" remove
  13. // slide over all others up through putIndex.
  14. final int putIndex = this.putIndex;
  15. for (int i = removeIndex;;) {
  16. int next = i + 1;
  17. if (next == items.length)
  18. next = 0;
  19. if (next != putIndex) {
  20. items[i] = items[next];
  21. i = next;
  22. } else {
  23. items[i] = null;
  24. this.putIndex = i;
  25. break;
  26. }
  27. }
  28. count--;
  29. if (itrs != null)
  30. itrs.removedAt(removeIndex);
  31. }
  32. notFull.signal();
  33. }

removeAt 的處理方式和我想的稍微有一點出入,它內部分為兩種情況來考慮:

  • removeIndex == takeIndex
  • removeIndex != takeIndex

也就是我考慮的時候沒有考慮邊界問題。當 removeIndex == takeIndex 時就不需要后面的元素整體往前移了,而只需要把 takeIndex的指向下一個元素即可(類比圓環);當 removeIndex != takeIndex 時,通過 putIndex 將 removeIndex 后的元素往前移一位。

四、總結

ArrayBlockingQueue 是一個阻塞隊列,內部由 ReentrantLock 來實現線程安全,由 Condition 的 await 和 signal 來實現等待喚醒的功能。它的數據結構是數組,準確的說是一個循環數組(可以類比一個圓環),所有的下標在到達最大長度時自動從 0 繼續開始。

到此這篇關于Java 并發編程ArrayBlockingQueue的實現的文章就介紹到這了,更多相關Java 并發編程ArrayBlockingQueue內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://juejin.cn/post/6930401738021961742

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 激情宗合 | 爱视频福利 | 欧美精品第1页 | www.guochan| 国产乱一区二区三区视频 | 日本娇小18xxxⅹhd | 电视剧全部免费观看 | 亚洲小视频在线播放 | 国产精品麻豆一区二区三区 | 国产精品午夜性视频 | 激情视频日韩 | 蜜桃视频在线免费观看 | 鲁久久| 亚洲乱妇19p| 久久国产综合视频 | 国产一级毛片网站 | 黄www片 | 在线播放的av网站 | 久久99国产精品免费网站 | 毛片一级片 | 欧美激情性色生活片在线观看 | av免费av | 91中文在线 | 韩国美女一区 | 成人性爱视频在线观看 | 亚洲生活片 | 久久久日韩精品一区二区 | 一级性色 | 欧洲伊人网 | 鲁丝一区二区二区四区 | 日本在线观看视频网站 | 欧美大胆xxxx肉体摄影 | 久久精品a一级国产免视看成人 | 在线观看91精品 | 一区二区三区黄色 | 中国国语毛片免费观看视频 | 国产午夜精品久久久久久久蜜臀 | 国产91在线高潮白浆在线观看 | 国产噜噜噜噜久久久久久久久 | 91精品国产一区二区在线观看 | 护士hd欧美free性xxxx |