在线观看www成人影院-在线观看www日本免费网站-在线观看www视频-在线观看操-欧美18在线-欧美1级

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

BlockingQueue主要屬性和構造函數

科技綠洲 ? 來源:Java技術指北 ? 作者:Java技術指北 ? 2023-10-13 11:36 ? 次閱讀

今天我們來聊一聊以數組為數據結構的阻塞隊列 ArrayBlockingQueue,它實現了 BlockingQueue 接口,繼承了抽象類 AbstractQueue。

BlockingQueue 提供了三個元素入隊的方法。

boolean add(E e);

boolean offer(E e);

void put(E e) throws InterruptedException;

三個元素出隊的方法。

E take() throws InterruptedException;

E poll(long timeout, TimeUnit unit)
        throws InterruptedException;

boolean remove(Object o);

一起來看看,ArrayBlockingQueue 是如何實現的吧。

初識

首先看一下 ArrayBlockingQueue 的主要屬性和構造函數。

屬性

//存放元素
final Object[] items; 

//取元素的索引
int takeIndex;

//存元素的索引
int putIndex;

//元素的數量
int count;

//控制并發的鎖
final ReentrantLock lock;

//非空條件信號
private final Condition notEmpty;

//非滿條件信號量
private final Condition notFull;

transient Itrs itrs = null;

從以上屬性可以看出:

  1. 以數組的方式存放元素。
  2. 用 putIndex 和 takeIndex 控制元素入隊和出隊的索引。
  3. 用重入鎖控制并發、保證線程的安全。

構造函數

ArrayBlockingQueue 有三個構造函數,其中 public ArrayBlockingQueue(int capacity, boolean fair, Collection c) 構造函數并不常用,暫且不提。看其中兩個構造函數。

public ArrayBlockingQueue(int capacity) {
    this(capacity, false);
}

public ArrayBlockingQueue(int capacity, boolean fair) {
    if (capacity <= 0)
        throw new IllegalArgumentException();
    //構造數組
    this.items = new Object[capacity];
    //默認以非公平鎖初始化 ReentrantLock
    lock = new ReentrantLock(fair);
    //創建兩個條件信號量
    notEmpty = lock.newCondition();
    notFull =  lock.newCondition();
}

可以看出 ArrayBlockingQueue 必須再創建時傳入數組的大小。

元素入隊

ArrayBlockingQueue 有 add()、offer()、put()、offer(E e, long timeout, TimeUnit unit) 方法用來元素的入隊。

add
//ArrayBlockingQueue.add()
public boolean add(E e) {
    //調用父類的 AbstractQueue.add() 方法
    return super.add(e);
}

//AbstractQueue.add()
public boolean add(E e) {
    //調用 ArrayBlockingQueue.offer(),成功則返回 true,否則拋出異常
    if (offer(e))
        return true;
    else
        throw new IllegalStateException("Queue full");
}

//ArrayBlockingQueue.offer()
public boolean offer(E e) {
    //非空檢查
    checkNotNull(e);
    //加鎖
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        //數組滿了,返回 false
        if (count == items.length)
            return false;
        else {
            //添加元素
            enqueue(e);
            return true;
        }
    } finally {
        //解鎖
        lock.unlock();
    }
}

//ArrayBlockingQueue.enqueue()
private void enqueue(E x) {
    final Object[] items = this.items;
    //直接放到 putIndex 的位置
    items[putIndex] = x;
    //如果索引滿了,putIndex 就從 0 開始,為什么呢?
    if (++putIndex == items.length)
        putIndex = 0;
    //數量加一
    count++;
    //數組里面有數據了,對 notEmpty 條件隊列進行通知
    notEmpty.signal();
}

上面留下了一個坑,索引等于數組的長度的時候,索引就從 0 開始了。其實很簡單,這個數組是不是先入先出的,0 索引的數組先入隊,也是先出隊的。這時候 0 索引的位置就空了,所以 putIndex 到達數組長度的時候就可以從 0 開始。這里可以看出,ArrayBlockingQueue 是絕對不可以修改數組長度的,一旦初始化后長度就不能再改變了。

put
//ArrayBlockingQueue.put()
public void put(E e) throws InterruptedException {
    //非空檢查
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    //加鎖
    lock.lockInterruptibly();
    try {
        //數組滿了,線程加入 notFull 隊列中等待被喚醒
        while (count == items.length)
            notFull.await();
        //添加元素
        enqueue(e);
    } finally {
        //解鎖
        lock.unlock();
    }
}
offer

ArrayBlockingQueue 中有兩個 offer() 方法,offer(E e) 和 offer(E e, long timeout, TimeUnit unit),add() 方法調用的就是 offer(E e) 方法。

//ArrayBlockingQueue.offer(E e, long timeout, TimeUnit unit)
public boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException {
    //非空檢查
    checkNotNull(e);
    //將時間轉換為納秒
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    //加鎖
    lock.lockInterruptibly();
    try {
        //當數組滿了
        while (count == items.length) {
            //時間到了,元素還沒有入隊,則返回 false
            if (nanos <= 0)
                return false; 
            //線程加入 notFull 隊列中,等待被喚醒,到達 nanos 時間返回剩余的 nanos 時間
            nanos = notFull.awaitNanos(nanos);
        }
        //元素入隊
        enqueue(e);
        return true;
    } finally {
        //解鎖
        lock.unlock();
    }
}

以上就是所有的元素入隊的方法,可以得出一些結論:

  1. add() 元素滿了,就拋出異常。
  2. offer() 元素滿了,返回 false。
  3. put() 元素滿了,線程阻塞等待被入隊。
  4. offer(E e, long timeout, TimeUnit unit) 加入超時時間,如果時間到了元素還是沒有被入隊,則返回 false

移除元素

ArrayBlockingQueue 提供了 poll()、take()、poll(long timeout, TimeUnit unit)、remove() 方法用于元素的出隊。

poll

ArrayBlockingQueue 中有兩個 poll() 方法,poll() 和 poll(long timeout, TimeUnit unit)。

//ArrayBlockingQueue.poll()
public E poll() {
    final ReentrantLock lock = this.lock;
    //加鎖
    lock.lock();
    try {
        //沒有元素返回 null,否則元素出隊
        return (count == 0) ? null : dequeue();
    } finally {
        lock.unlock();
    }
}

//ArrayBlockingQueue.dequeue()
private E dequeue() {
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    //獲取 takeIndex 上的元素
    E x = (E) items[takeIndex];
    //設置 takeIndex 索引上的元素為 null
    items[takeIndex] = null;
    //當 takeIndex 長度是數組長度,takeIndex 索引從 0 開始
    if (++takeIndex == items.length)
        takeIndex = 0;
    //元素數量 -1
    count--;

    if (itrs != null)
        //更新迭代器
        itrs.elementDequeued();
    //喚醒 notFull 的等待隊列,其中等待的第一個線程可以添加元素了
    notFull.signal();
    return x;
}
//ArrayBlockingQueue.poll(long timeout, TimeUnit unit)
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    ////將時間轉換為納秒
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    //加鎖
    lock.lockInterruptibly();
    try {
        //數組為空,超時還沒有元素出隊,則返回 null
        while (count == 0) {
            if (nanos <= 0)
                return null;
            //線程加入 notEmpty 中,等待被喚醒,到達 nanos 時間返回剩余的 nanos 時間
            nanos = notEmpty.awaitNanos(nanos);
        }
        //元素出隊
        return dequeue();
    } finally {
        lock.unlock();
    }
}
take
//ArrayBlockingQueue.take()
public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    //加鎖
    lock.lockInterruptibly();
    try {
        //無元素
        while (count == 0)
            //將線程加入 notEmpty 的等待隊列中,等待被入隊的元素喚醒
            notEmpty.await();
        //元素出隊
        return dequeue();
    } finally {
        //解鎖
        lock.unlock();
    }
}
remove
//ArrayBlockingQueue.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 {
                //找到元素
                if (o.equals(items[i])) {
                    removeAt(i);
                    return true;
                }
                //i 等于數組長度的時候,從 0 開始
                if (++i == items.length)
                    i = 0;
            // i == putIndex 說明已經遍歷了一遍
            } while (i != putIndex);
        }
        return false;
    } finally {
        //解鎖
        lock.unlock();
    }
}

//ArrayBlockingQueue.removeAt()
void removeAt(final int removeIndex) {
    final Object[] items = this.items;
    //需要出隊的 removeIndex 正好是 takeIndex
    if (removeIndex == takeIndex) {
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        //更新迭代器
        if (itrs != null)
            itrs.elementDequeued();
    } else {
        final int putIndex = this.putIndex;
        // 循環移動元素,將 next 元素向前移動 1 個
        for (int i = removeIndex;;) {
            int next = i + 1;
            if (next == items.length)
                next = 0;
            if (next != putIndex) {
                items[i] = items[next];
                i = next;
            } else {
                //設置 i 索引的位置為空,putIndex 索引為 i
                items[i] = null;
                this.putIndex = i;
                break;
            }
        }
        count--;
        if (itrs != null)
            itrs.removedAt(removeIndex);
    }
    // 喚醒 notFull 隊列中等待的線程,通知可以元素入隊了
    notFull.signal();
}

以上就是所有的元素出隊的方法,可以得出一些結論:

  1. poll() 元素出隊為空,則返回空
  2. take() 元素出隊為空的時候,會阻塞線程
  3. remove() 元素出隊的時候可能會移動數組
  4. poll(long timeout, TimeUnit unit) 加入超時時間,如果時間到了還是沒有元素需要出隊,則返回 null

總結

ArrayBlockingQueue 可以被用在生產者和消費者模型中。

  1. ArrayBlockingQueue,不能被擴容,初始化被指定容量。
  2. 利用 putIndex 和 takeIndex 循環利用數組。
  3. 利用了 ReentrantLock 和 兩個 Condition 保證了線程的安全。
聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • 接口
    +關注

    關注

    33

    文章

    8961

    瀏覽量

    153264
  • 函數
    +關注

    關注

    3

    文章

    4372

    瀏覽量

    64288
  • 數據結構
    +關注

    關注

    3

    文章

    573

    瀏覽量

    40623
  • 數組
    +關注

    關注

    1

    文章

    419

    瀏覽量

    26393
收藏 人收藏

    評論

    相關推薦
    熱點推薦

    SystemVerilog中的類構造函數new

    在systemverilog中,如果一個類沒有顯式地聲明構造函數(new()),那么編譯仿真工具會自動提供一個隱式的new()函數。這個new函數會默認地將所有
    發表于 11-16 09:58 ?3926次閱讀

    什么是構造函數?怎樣去編寫構造函數

    什么是構造函數?怎樣去編寫構造函數呢?
    發表于 02-22 08:31

    一個基于多屬性協商的效用函數研究

    傳統的效用函數模型還不能滿足多屬性協商中反映協商屬性間的關聯關系的內在要求,束縛了自動協商的應用。本文闡述了自動協商的相關知識背景,分析了多屬性協商的特征和協
    發表于 01-22 14:22 ?11次下載

    基于生成函數的格雷對分析與構造

    該文由傳統的格雷對構造方法交織和級聯出發,提出了一種新的稱之為生成函數的格雷對構造方法,該方法適用于長度為2n 的格雷對。文中分析了格雷對生成函數和希爾維斯特Hadamard
    發表于 02-08 16:04 ?8次下載

    基于plateaued函數的平衡布爾函數構造

    不相交plateaued函數,一類特殊的布爾置換以及一個高非線性度平衡函數,提出了一個構造高非線性度平衡布爾函數的方法。通過分析可知,利用該方法可以
    發表于 12-17 09:43 ?0次下載

    如何深度解析C++拷貝構造函數詳細資料說明

    本文檔的主要內容詳細介紹的是如何深度解析C++拷貝構造函數詳細資料說明。
    發表于 07-05 17:41 ?0次下載
    如何深度解析C++拷貝<b class='flag-5'>構造</b><b class='flag-5'>函數</b>詳細資料說明

    Linux共享庫的構造函數和析構函數

    共享庫有類似C++類構造和析構函數函數,當動態庫加載和卸載的時候,函數會被分別執行。一個函數加上 constructor的 attribu
    的頭像 發表于 06-22 09:18 ?2490次閱讀
    Linux共享庫的<b class='flag-5'>構造</b><b class='flag-5'>函數</b>和析構<b class='flag-5'>函數</b>

    類的拷貝構造函數主要用途是什么?

    類在實例化的時候會調用類的缺省構造函數,在struct里,要定義一個同名函數指針指向一個具有構造函數功能的初始化
    的頭像 發表于 06-24 14:28 ?5029次閱讀

    C++:詳談構造函數

    構造函數是一個特殊的成員函數,名字與類名相同,創建類類型對象的時候,由編譯器自動調用,在對象的生命周期內只且調用一次,以保證每個數據成員都有一個合適的初始值。
    的頭像 發表于 06-29 11:44 ?1933次閱讀
    C++:詳談<b class='flag-5'>構造</b><b class='flag-5'>函數</b>

    C++:詳談拷貝構造函數

    只有單個形參,而且該形參是對本類類型對象的引用(常用const修飾),這樣的構造函數稱為拷貝構造函數。拷貝構造
    的頭像 發表于 06-29 11:45 ?2287次閱讀
    C++:詳談拷貝<b class='flag-5'>構造</b><b class='flag-5'>函數</b>

    C++之拷貝構造函數的淺copy及深copy

    C++編譯器會默認提供構造函數;無參構造函數用于定義對象的默認初始化狀態;拷貝構造函數在創建對象
    的頭像 發表于 12-24 15:31 ?956次閱讀

    c++中構造函數學習的總結(一)

    關于這個構造函數,簡單理解就是在一個類中,有一個函數,它的函數名稱和類名同名,而且這個構造函數
    的頭像 發表于 12-24 18:06 ?914次閱讀

    基于布爾函數導數的布爾置換構造

    布爾函數導數的性質在密碼構造中起著重要的作用。文中利用布爾函數導數的性質,構造了一個新的平衡布爾函數然后基于平衡布爾
    發表于 06-17 10:58 ?15次下載

    2.10 學生類-構造函數 (15分)

    )。 ###1.編寫有參構造函數: 能對name,sex,age賦值。 ###2.覆蓋toString函數:按照格式:類名 [name=, sex=, age=]輸出。使用idea自動生成,然后在修改成該輸出格式 ###3.對每
    發表于 12-29 19:05 ?1次下載
    2.10 學生類-<b class='flag-5'>構造</b><b class='flag-5'>函數</b> (15分)

    深入探索GCC的attribute屬性

    修飾變量、函數或者數據類型的屬性屬性有很多,有些確實很有用。 找了幾個可以修飾函數屬性,供大家參考下。 如果希望
    的頭像 發表于 02-13 10:05 ?351次閱讀
    主站蜘蛛池模板: www.色在线观看 | 亚洲精品视频区 | 男人的j桶女人的j视频 | 大尺度在线播放 | 久久美女免费视频 | 天天爽夜夜爽精品免费 | 日本亚洲一区二区 | 日本高清视频色wwwwww色 | 老头天天吃我奶躁我的动图 | 久久免费视频2 | 日一日操一操 | 日本媚薬痉挛在线观看免费 | 免费视频在线播放 | 久久瑟 | 最新天堂网 | 四虎国产永久免费久久 | 激情综合激情五月 | 一卡二卡≡卡四卡亚洲高清 | 五月婷婷久久综合 | 天天操夜 | 中文字幕在线观看你懂的 | 久久草在线播放 | 视频在线观看免费播放www | 华人黄网站大全 | 好爽的视频黄 | bt天堂网www连接 | 啪啪91视频| 欧美一区二区三区成人看不卡 | 美女扒开尿口给男人爽免费视频 | 免费视频精品 | 国产欧美另类第一页 | 免费人成网站线观看合集 | 香蕉久久久久久狠狠色 | 手机在线色 | 特级毛片免费视频播放 | 国产一区二区三区波多野吉衣 | 国产精品www夜色影视 | 自拍偷拍福利视频 | 日本天天操 | 免费免播放器在线视频观看 | 欧美一级欧美三级在线 |