java队列,ArrayBlockingQueue

时间:2022-04-29
本文章向大家介绍java队列,ArrayBlockingQueue,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

提供了三个构造方法:    ①.ArrayBlockingQueue(int capacity)//指定长度,默认加锁机制为非公平锁    ②.ArrayBlockingQueue(int capacity, boolean fair)//显示指定使用公平锁或非公平锁    ③.ArrayBlockingQueue(int capacity, boolean fair,Collection<? extends E> c) //可以传入一个集合 全局变量:  final Object[] items;//queue维护了一个定长数组用来当对象容器,在初始化时创建  int takeIndex;  int putIndex;  int count;//容器的大小  final ReentrantLock lock;//显示锁  private final Condition notEmpty;//用来做线程通信,若队列已空则阻塞  private final Condition notFull;//判断是否已满,满则阻塞

方法:

 /**添加**/
 public void put(E e) throws InterruptedException {
        checkNotNull(e);//非空检查,若为空抛异常
        final ReentrantLock lock = this.lock;//加锁
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();//队列满了阻塞.
            insert(e);//否则添加
        } finally {
            lock.unlock();
        }
    }

private void insert(E x) {
        items[putIndex] = x;
        putIndex = inc(putIndex);
        ++count;
        notEmpty.signal();//唤醒消费线程
    }


 final int inc(int i) {//返回下一个该添加的位置,若满则从0开始
        return (++i == items.length) ? 0 : i;
    }


 /**取**/
 public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();//没有可消费对象阻塞
            return extract();//获取
        } finally {
            lock.unlock();
        }
    }

private E extract() {
        final Object[] items = this.items;
        E x = this.<E>cast(items[takeIndex]);//获取一个强转对象
        items[takeIndex] = null;/清除容器中这个元素
        takeIndex = inc(takeIndex);//下一个可取的位置
        --count;
        notFull.signal();//唤醒生产线程
        return x;
    }

以上是几个常用的方法, 其他方法差别不大.