[java队列]——ArrayBlockingQueue

队列

队列就是一种先进先出(FIFO)的线性表

ArrayBlockingQueue简介

  • 数组实现
  • 线程安全
  • 不需要扩容,数组大小固定
  • 位于java并发包下

ArrayBlockingQueue内部实现

基本属性

package java.util.concurrent;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.ref.WeakReference;
import java.util.Spliterators;
import java.util.Spliterator;


public class ArrayBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
    private static final long serialVersionUID = -817911632652898426L;

    //存储队列元素的数组
    final Object[] items;

    //记录每次待取元素的位置指针
    int takeIndex;

    //记录每次待存元素的位置指针
    int putIndex;

    //队列元素个数
    int count;
    
    //可重入锁,对以下两个Condition的并发控制
    final ReentrantLock lock;

    //非空条件
    private final Condition notEmpty;

    //非满条件
    private final Condition notFull;

结论:

  • 通过存、取指针来记录下一次要操作的位置
  • 用数组存储元素
  • 利用可重入锁来对两个Condition做并发控制

构造方法

	//只传入队列容量
    public ArrayBlockingQueue(int capacity) {
    	//默认使用非公平锁
        this(capacity, false);
    }
    //传入队列容量和是否使用公平锁
    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();
    }
	//传入容量、是否使用公平锁,以及要存入的集合元素
    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();
        }
    }

结论:

  • 可通过构造方法选择可重入锁是否使用公平锁
  • 可通过构造方法设置队列的容量

入队

入队提供的方法
在这里插入图片描述

add(E e)方法

//ArrayBlockingQueue的add方法
public boolean add(E e) {
        return super.add(e);
    }

//父类中的add方法 super.add(e) 如下
public boolean add(E e) {
		//调用子类(ArrayBlockingQueue)的offer方法
        if (offer(e))
            return true;
        else
        	//可以看到add方法,如果入队失败是会抛异常的	
            throw new IllegalStateException("Queue full");
    }

offer(E e)方法

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

put(E e)方法

public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        //加锁,如果被中断抛出InterruptedException异常
        lock.lockInterruptibly();
        try {
            while (count == items.length)
            	//如果队列满了。则等待notFull(非满)条件,阻塞直到队列为非满才返回
                notFull.await();
            //真正的入队方法
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

offer(E e, long timeout, TimeUnit 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)
                	//如果时间到了,仍然后没有空间,直接返回false
                    return false;
                //阻塞等待nanos时间后返回
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(e);
            return true;
        } finally {
            lock.unlock();
        }
    }

真正的入队——enqueue(E x)方法

private void enqueue(E x) {
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
        	//当存指针达到数组末尾时,指针位置重新设置为0
        	//从这里可以看出是使用循环数组
            putIndex = 0;
        count++;
        //存完元素后,发出数组内元素非空信号
        notEmpty.signal();
    }

结论:

  • add方法其实是调用offer方法,如果队列满了入队失败抛异常,不阻塞
  • offer方法入队成功返回true,队列满了入队返回false,不阻塞
  • offer timeout方法,阻塞一段时间后,若队列仍满,无法入队则返回fasles
  • put方法,若队列满,一直阻塞,直到队列非满入队才返回true,或者线程被中断才抛出中断异常

出队

与入队类似,出队也有四个方法remove()、poll()、take()、poll(long timeout, TimeUnit unit),由于实现方式与入队非常类似,这里直接贴源码不做注释,大家可以自己研读一下。非常易读

	//这个方法在ArrayBlcokingQueue的父类AbstractQueue中
	public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } 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();
        }
    }

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

结论:

  • remove方法,如果队列为空出队失败则抛出异常
  • poll方法,如果队列为空出队失败则返回false
  • poll timeout方法,阻塞一段时间,如果队列仍然为空,则返回false
  • take方法,如果队列为空,一直阻塞,直到队列不为空才返回,或者线程被中断才抛出中断异常

ArrayBlockingQueue总结

实现:

  • 数组实现
  • 线程安全,利用可重入锁控制非空和非满两个Condition进行并发控制
  • 不需要扩容,数组大小固定,利用循环数组
    缺点:
  • 队列长度在初始化时指定,并且不会自动扩容,选择容量时需谨慎
  • 若队列长期为空或者为满,会导致对应的取、存线程一直处于阻塞,阻塞线程会越变越多
  • 只使用一个锁来控制,并发效率低

BlockingQueue接口

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable

可以看到ArrayBlockingQueue实现了BlockingQueue接口,那么BlockingQueue接口定义了哪些方法呢。
在这里插入图片描述
下面分析一下其中的一些方法和区别

队列操作 正常返回特定值 可能抛出异常 阻塞超时返回 长期阻塞
入队 add offer put offer(e,timeoute,unit)
出队 remove poll take poll(timeout,unit)
检查 element peek —— ——
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章