Queue.ArrayBlockQueue

#ArrayBlockQueuejava

  • 見名知義,數組結構,阻塞隊列,線程安全
  • 內部結構
//存儲數組
    final Object[] items;
    //取索引
    int takeIndex;
    //插索引
    int putIndex;
    //元素容量
    int count;
    //同步鎖
    final ReentrantLock lock;
    //取阻塞條件
    private final Condition notEmpty;
    //插入阻塞條件
    private final Condition notFull;
  • put 方法,插入,滿則等待
//lock 優先考慮獲取鎖,待獲取鎖成功後,才響應中斷。
//lockInterruptibly 優先考慮響應中斷,而不是響應鎖的普通獲取或重入獲取
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();
        }
    }
public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
  • TODO 遍歷過程,同步,操做指針
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息