ArrayBlockingQueue源码解读

    //指定队列大小
    public ArrayBlockingQueue(int capacity)
    //指定队列大小、访问策略
    //fair如果为 true,则按照 FIFO 顺序访问插入或移除时受阻塞线程的队列;如果为 false,则访问顺序是不确定的。
    public ArrayBlockingQueue(int capacity, boolean fair)
    //指定队列大小、访问策略、初始元素 
    //包含给定 collection 的元素,并以 collection 迭代器的遍历顺序添加元素。
    public ArrayBlockingQueue(int capacity, boolean fair,Collection<? extends E> c)
    //ArrayBlockingQueue的三种构造函数,均指定了容量大小

    //真正存入数据的数组
    final Object[] items;
    //下一个被取出元素的索引
    int takeIndex;
    //下一个被添加元素的索引
    int putIndex;
    //队列中元素个数
    int count;
    // 整个消息队列的锁
    final ReentrantLock lock;
    //出队的条件
    private final Condition notEmpty;
    //入队的条件
    private final Condition notFull;


//循环队列的实现:对i进行加1操作
final int inc(int i) {
        return (++i == items.length) ? 0 : i;
        //若++i的值等于队列的长度,则设置“下一个被添加元素的索引”为0,否则为i
    }
//循环队列的实现:对i进行减1操作
final int dec(int i) {
        return ((i == 0) ? items.length : i) - 1;
         //i为零时,让i指向最后一个元素
    }
private void insert(E x) {
        items[putIndex] = x;//在当前putIndex的位置存放x的值
        putIndex = inc(putIndex);//保存下一个putIndex的位置
        ++count;//队列元素个数加1
        notEmpty.signal();//发送非空信号 唤醒取元素线程
    }
  private E extract() {
        final Object[] items = this.items;
        E x = this.<E>cast(items[takeIndex]);
        items[takeIndex] = null;//将当前位置的元素设为null
        takeIndex = inc(takeIndex);//保存下一个取元素的位置
        --count;//队列元素个数减1
        notFull.signal();//发送非满信号 唤醒存元素线程
        return x;//返回取到的值
    }

 void removeAt(int i) {  
      final Object[] items = this.items;  
      //如果准备移除的索引和下一个被取出的元素索引一样,直接移除  
      if (i == takeIndex) {  
          //赋值null,便于GC  
          items[takeIndex] = null;  
          //重新设置下一个被取出元素的索引  
          takeIndex = inc(takeIndex);  
      //如果需要删除的元素索引不是当前被取出的索引  
      } else {  
          //一直循环,直到删除为止  
          for (;;) {  
              //假设队列容量是4,目前存了3个元素,即takeIndex=0,putIndex=3,目前我打算删除数组下标为1的元素  
              // nexti第一次为2  
              int nexti = inc(i);  
              if (nexti != putIndex) {  
                  //相当于将队列往前移  
                  items[i] = items[nexti];  
                  //相当于i+1  
                  i = nexti;  
              //待删除的索引与待put的索引相等,比如putIndex=2,i=1,inc(i) = 2  
              } else {  
                  //索引i处置null 
                  items[i] = null;  
                  //重新赋值下一个即将放入元素的索引  
                  putIndex = i;  
                  break;  
              }  
          }  
      }  
      //队列大小-1  
      --count;  
      //唤醒put线程,公平的话按FIFO顺序,非公平的话可以抢占  
      notFull.signal();  
  }  
//存放元素
public boolean offer(E e) {
    checkNotNull(e);//检查元素不能为空
    final ReentrantLock lock = this.lock;
    lock.lock();//获取锁
    try {
        if (count == items.length)//若当前元素个数等于数组长度,返回false
            return false;
        else {
            insert(e); //队列未满,插入元素并返回true
            return true;
        }
    } finally {
        lock.unlock();//释放锁
    }
}

public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();// 如果当前线程未被中断,则获取锁
        try {
            while (count == items.length)// 判断元素是否已满
                notFull.await();//等待一个notFull信号,并释放锁
            insert(e);         //收到notFull信号,会重新获得锁,并再一次执行while语句
        } finally {
            lock.unlock(); //释放锁
        }
    }

//带有超时等待时间的插入方法,timeout表示等待的时间,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) {
                if (nanos <= 0)//指定时间内未收到通知,返回0或负数
                    return false;
                //返回nanos>0,说明收到了signal()信号,继续while条件检测
                nanos = notFull.awaitNanos(nanos); 
            }
            insert(e);
            return true;
        } finally {
            lock.unlock();//释放锁
        }
    }

public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
           // 若元素个数为0则返回null,否则,调用extract,出队列
            return (count == 0) ? null : extract();
        } finally {
            lock.unlock();
        }
    }
 public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();// 如果当前线程未被中断,则获取锁,中断会抛出异常
        try {
            while (count == 0)// 元素数量为0
                notEmpty.await();// 等待一个notEmpty信号,并释放锁
            return extract();//出队列
        } finally {
            lock.unlock();//释放锁
        }
    }
public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
        //元素个数为0,返回null,否则根据下一个将要出队的元素下标得到该元素的值
            return (count == 0) ? null : itemAt(takeIndex);
        } finally {
            lock.unlock();
        }
    }
 //用于移除此队列中所有可用的元素,并将它们添加到给定 collection 中。
 public int drainTo(Collection<? super E> c) {
        checkNotNull(c);
        //如果指定 collection 是此队列,或者此队列元素的某些属性不允许将其添加到指定 collection 抛出异常   
        if (c == this)
            throw new IllegalArgumentException();
        final Object[] items = this.items;
        final ReentrantLock lock = this.lock;
        //获取锁 
        lock.lock();
        try {
            //take操作的位置  
            int i = takeIndex;
            int n = 0;
            //元素数量  
            int max = count;
            //利用循环不断取出元素添加到c中  
            while (n < max) {
                c.add(this.<E>cast(items[i]));
                items[i] = null;
                i = inc(i);
                ++n;
            }
            //添加完成后初始化必要值,唤醒添加线程
            if (n > 0) {
                count = 0;
                putIndex = 0;
                takeIndex = 0;
                notFull.signalAll();
            }
             //返回添加元素数量 
            return n;
        } finally {
            //释放锁 
            lock.unlock();
        }

 drainTo(Collection<? super E> c, int maxElements)用法类似,只不过指定了移除元素数。

总结:
1.ArrayBlockingQueue继承于AbstractQueue,并且它实现了BlockingQueue接口。
2ArrayBlockingQueue 底层是基于数组实现的队列,容量指定后,不会改变。
3.ArrayBlockingQueue 是一种逻辑上的环形队列。
4.ArrayBlockingQueue 不接受 null 元素。
5.ArrayBlockingQueue是线程安全的,通过ReentrantLock来完成。
6.ArrayBlockingQueue 在入队和出队上都使用了同一个重入锁,因此入队和出队是不能并发执行的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值