阻塞队列:ArrayBlockingQueue

阻塞队列很好的解决了多线程中数据的安全传输问题,其中最典型的例子就是客园很好的解决“生产者--消费者”问题。

下面来看其中一个实现类ArrayBlockingQueue。看到这个名字,就很好理解这个队列肯定是使用数组实现的队列,即使用数组实现的“先进先出”的队列,下面看其具体的实现。

一、构造函数

/**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity and default access policy.
     *
     * @param capacity the capacity of this queue
     * @throws IllegalArgumentException if {@code capacity < 1}
     */
    public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }

    /**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity and the specified access policy.
     *
     * @param capacity the capacity of this queue
     * @param fair if {@code true} then queue accesses for threads blocked
     *        on insertion or removal, are processed in FIFO order;
     *        if {@code false} the access order is unspecified.
     * @throws IllegalArgumentException if {@code capacity < 1}
     */
    public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

    /**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity, the specified access policy and initially containing the
     * elements of the given collection,
     * added in traversal order of the collection's iterator.
     *
     * @param capacity the capacity of this queue
     * @param fair if {@code true} then queue accesses for threads blocked
     *        on insertion or removal, are processed in FIFO order;
     *        if {@code false} the access order is unspecified.
     * @param c the collection of elements to initially contain
     * @throws IllegalArgumentException if {@code capacity} is less than
     *         {@code c.size()}, or less than 1.
     * @throws NullPointerException if the specified collection or any
     *         of its elements are null
     */
    public ArrayBlockingQueue(int capacity, boolean fair,
                              Collection<? extends E> c) {
        this(capacity, fair);

        final ReentrantLock lock = this.lock;
        lock.lock(); // Lock only for visibility, not mutual exclusion
        try {
            int i = 0;
            try {
                for (E e : c) {
                    checkNotNull(e);
                    items[i++] = e;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException();
            }
            count = i;
            putIndex = (i == capacity) ? 0 : i;
        } finally {
            lock.unlock();
        }
    }

1.public ArrayBlockingQueue(int capacity)

接收一个整型的参数,这个整型参数指的是队列的长度。

2.public ArrayBlockingQueue(int capacity, boolean fair)

接收一个整型的参数和一个boolean值,第一个参数上面解释过了,第二个参数是作为可重入锁的参数进行初始化,规定可重入锁是公平还是不公平,默认为false,另外初始化了notEmpty、notFull两个信号量。

3.public ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)

前两个参数上面解释过了,第三个参数传入一个集合,会循环添加到队列中。

二、队列的操作

需要使用阻塞队列,那么就需要向队列中添加或取出元素,在ArrayBlocking中已经实现了相关操作,对于添加/取出均是成对出现,提供的方法中有抛出异常、返回false、线程阻塞等几种情形。

1、add/peek

add/peek是一对互斥的操作,add向队列种放入元素,peek取出元素。

1.1、add

public boolean add(E e) {
        return super.add(e);
}

//继承父类:父类实现种调用的offer方法,在offer方法返回true时,add方法返回true,其他则抛出“Queue full”的异常。offer方法下面会讲到。

public boolean add(E e) {
    if (offer(e))
         return true;
     else
        throw new IllegalStateException("Queue full");
}

 

1.2、peek

public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return itemAt(takeIndex); // null when queue is empty
        } finally {
            lock.unlock();
        }
}

在peek方法种使用可重入锁,返回takeIndex处的元素,前面注释中写道,此变量代表的是待取出元素的索引。itemAt方法定义如下, 

final E itemAt(int i) {
        return (E) items[i];
    }

此方法未进行任何的判断直接返回takeIndex出的数组元素。 

2、put/take

put/take是一对互斥的操作,put向队列种放入元素,take取出元素,其实现方式和add/peek不一样。

2.1、put

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();
        }
    }

此方法会判断元素是否null,然后判断当前队列中的元素数量和队列的长度,如果二者相等则阻塞当前线程;如果不相等则执行enqueue(e)方法,其定义如下,

private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }

把待插入的元素放在数组的putIndex位置,如果执行完插入后putIndex等于数组的长度,说明队列已经满了,那么把putIndex的值置为0,即下次插入的位置为0,下次要插入成功的必要条件是取出了一个元素,取出的位置为takeIndex。

2.2、take

public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

此方法中首先判断当前队列的元素数量如果为0,则当前线程进行等待,等待notEmpty.singal(),如果不为空则执行dequeue()方法,其定义如下,

private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

此方法取出takeIndex位置的元素,把数组中此位置的引用置为null,判断takeIndex和数组的长度,如果相等证明,已经取到了最后一个元素,下次再取元素需要从位置0开始,为此把takeIndex置为0。

3、offer(E)/poll

offer/poll是一对互斥的操作,offer向队列种放入元素,poll取出元素,

3.1、offer

public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

此方法判断如果队列中的元素数量和队列长度相等,则直接返回false,否则执行enqueue方法,put方法会将线程挂起,直到被中断或插入成功。

3.2、poll

public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }

 

此方法判断当前队列中的元素个数如果为0返回null,否则执行dequeue操作,take方法会将线程挂起,直到被中断或取出成功。

4、offer(E,long,TimeUnit)/poll(long,TimeUnnit)

 这两个方法是普通offer/poll方法的加强版,在队列满时指定了重试的时间,如果超过指定的时间后还是无法添加或取出则返回false。

4.1、offer

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)
                    return false;//超过规定时间,返回false
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(e);
            return true;
        } finally {
            lock.unlock();
        }
    }

 

此方法会在指定的规定时间内一直重试,如果规定时间内无法退出循环即添加元素,则返回false。

4.2、poll

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

 

此方法同样是在取出元素时进行规定时间的重试,超过规定时间则返回null。

Demo

输出 

三、方法比较

1、添加方法比较

序号方法名队列满时处理方式方法返回值
1add(E e)抛出“Queue full”异常boolean
2offer(E e)返回falseboolean
3put(E e)线程阻塞,直到中断或被唤醒void
4offer(E e, long timeout, TimeUnit unit)在规定时间内重试,超过规定时间返回falseboolean

2、取出方法比较

序号方法名队列空时处理方式方法返回值
1peek()返回nullE
2poll()返回nullE
3take()线程阻塞,指定中断或被唤醒E
4poll(long timeout, TimeUnit unit)在规定时间内重试,超过规定时间返回nullE

四、总结

以上时关于ArrayBlockingQueue这个阻塞队列的相关实现及方法介绍,此队列以数组为载体,配合可重入锁实现生产线程和消费线程共享数据,ArrayBlockingQueue作为共享池,实现了并发条件下的添加及取出等方法。

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值