您的位置:首页 > 产品设计 > UI/UE

ArrayBlockingQueue源码解析

2018-01-27 23:24 344 查看
ArrayBlockingQueue通过数组进行存储。通过标记putIndex实现进行找到添加入队元素位置;通过标记takeIndex进行找到出队元素位置;通过count记录队列元素,如果count=数组的长度则队列已经满,如果count=0则队列为空的。

如果队列入队标记位置已经到数组末尾则从数组头开始。---这样进行循环

如果队列出队标记位置已经到数组末尾则从数组头开始。---这样进行循环

 /** The queued items */

    final Object[] items;

    /** items index for next take, poll, peek or remove */

    int takeIndex;

    /** items index for next put, offer, or add */

    int putIndex;

    /** Number of elements in the queue */

    int count;

    /*

     * Concurrency control uses the classic two-condition algorithm

     * found in any textbook.

     */

    /** Main lock guarding all access */

    final ReentrantLock lock;

    /** Condition for waiting takes */

    private final Condition notEmpty;

    /** Condition for waiting puts */

    private final Condition notFull;

    // Internal helper methods

    /**

     * Circularly increment i.

     */

    final int inc(int i) {

        return (++i == items.length) ? 0 : i;//如果队列put标记位置已经到数组末尾则从数组头开始。---这样进行循环

    }

    /**

     * Circularly decrement i.

     */

    final int dec(int i) {

        return ((i == 0) ? items.length : i) - 1;

    }

    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;//队列个数加1

        notEmpty.signal();//激活在take出队阻塞的线程

    }

    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();//通知put阻塞线程

        return x;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息