新聞中心
這期內(nèi)容當中小編將會給大家?guī)碛嘘P(guān)ArrayBlockingQueue知識點有哪些,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
治多ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)建站的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!
JDK1.8版本,整理有關(guān)ArrayBlockingQueue的知識點,并對其中主要的方法進行分析
特點
1.有界隊列(基于數(shù)組實現(xiàn)的)
2.先進先出
3.如果隊列滿了,put操作會阻塞;如果隊列空了,take操作會阻塞。
4.支持公平或者非公平的策略(因為內(nèi)部是使用ReentrantLock來實現(xiàn)阻塞的),公平策略(降低吞吐量)
5.使用經(jīng)典的雙條件算法來保證阻塞功能
6.寫數(shù)據(jù)和消費數(shù)據(jù)使用同一把鎖(這就導致寫數(shù)據(jù)和消費數(shù)據(jù)并不能真正的并發(fā))
主要方法
1.add(),offer(),put()方法
三者都是插入方法,add()時如果隊列滿了,會拋出異常;offer()如果隊列滿了,返回false;put方法,如果隊列滿了,阻塞等待
add()方法: public boolean add(E e) { return super.add(e);//調(diào)用父類的add(),父類中又調(diào)用了offer()方法,所以最終還是調(diào)用offer()方法 } offer()方法 public boolean offer(E e) { checkNotNull(e); //判斷元素是否為空 final ReentrantLock lock = this.lock; lock.lock();//獲取鎖 try { if (count == items.length) //判斷隊列是否已滿,如果滿了 直接返回 false return false; else { enqueue(e); //放入隊列中 return true; } } finally { lock.unlock(); //釋放鎖 } } put()方法 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(); // 釋放鎖 } }
2.poll(),take(),peek()方法
三者都是元素出隊方法
1.peek()取出元素,但不會刪除元素
2.poll()取出元素,并刪除元素
3.take()取出元素,并且刪除,如果隊列為空的話,阻塞當前操作
1.peek()方法 public E peek() { final ReentrantLock lock = this.lock; lock.lock(); //獲取鎖 try { return itemAt(takeIndex); // 獲取元素 } finally { lock.unlock(); //釋放鎖 } } 2.poll() public E poll() { final ReentrantLock lock = this.lock; lock.lock();//獲取鎖 try { return (count == 0) ? null : dequeue(); //獲取元素,并且刪除元素 } finally { lock.unlock();//釋放鎖 } } 3.take() public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly();//獲取鎖 try { while (count == 0) //隊列為空阻塞 notEmpty.await(); return dequeue(); //獲取元素,并刪除 } finally { lock.unlock(); //釋放鎖 } }
3.remove()方法
remove()移除元素,使用循環(huán)的方式移除
1.remove()方法 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 { //循環(huán),直到找到要刪除的元素 if (o.equals(items[i])) { removeAt(i); return true; } if (++i == items.length) i = 0; } while (i != putIndex); } return false; } finally { lock.unlock(); //釋放鎖 } }
上述就是小編為大家分享的ArrayBlockingQueue知識點有哪些了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站標題:ArrayBlockingQueue知識點有哪些
轉(zhuǎn)載來源:http://www.ef60e0e.cn/article/jggooj.html