一:对于BlockQueue的认识:

1:
阻塞队列是一个支持两个附加操作的队列,这两个附加的操作支持阻塞的插入与移除方法。
其实就是为了满足生产者消费者模式的容器设计,当队列满时,阻塞添加,当队列空时,阻塞获取,
其内部的实现原理其实就是基于Condition的等待通知机制,比如ArrayBlockingQueue,这个已经在前面分析过了,所以这篇只需要了解掌握各种阻塞队列的特点就行。

2:基本操作
clipboard400.pngBlockingQueue继承于Queue接口,因此,对数据元素的基本操作有:
插入元素

  1. add(E e) :往队列插入数据,当队列满时,插入元素时会抛出IllegalStateException异常;
  2. offer(E e):当往队列插入数据时,插入成功返回true,否则则返回false。当队列满时不会抛出异常;

删除元素

  1. remove(Object o):从队列中删除数据,成功则返回true,否则为false
  2. poll:删除数据,当队列为空时,返回null;

查看元素

  1. element:获取队头元素,如果队列为空时则抛出NoSuchElementException异常;
  2. peek:获取队头元素,如果队列为空则抛出NoSuchElementException异常

BlockingQueue具有的特殊操作:
插入数据:

  1. put:当阻塞队列容量已经满时,往阻塞队列插入数据的线程会被阻塞,直至阻塞队列已经有空余的容量可供使用;
  2. offer(E e, long timeout, TimeUnit unit):若阻塞队列已经满时,同样会阻塞插入数据的线程,直至阻塞队列已经有空余的地方,与put方法不同的是,该方法会有一个超时时间,若超过当前给定的超时时间,插入数据的线程会退出;

删除数据

  1. take():当阻塞队列为空时,获取队头数据的线程会被阻塞;
  2. poll(long timeout, TimeUnit unit):当阻塞队列为空时,获取数据的线程会被阻塞,另外,如果被阻塞的线程超过了给定的时长,该线程会退出。

3:常用的BlockingQueue:
实现BlockingQueue接口的有ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedTransferQueue, PriorityBlockingQueue, SynchronousQueue,而这几种常见的阻塞队列也是在实际编程中会常用的,
下面对这几种常见的阻塞队列进行说明: 也可以看书上的总结,相差不大,这里直接copy作者总结的。

二:各种阻塞队列的介绍

1.ArrayBlockingQueue
ArrayBlockingQueue是由数组实现的有界阻塞队列。该队列命令元素FIFO(先进先出)。因此,对头元素时队列中存在时间最长的数据元素,而对尾数据则是当前队列最新的数据元素。ArrayBlockingQueue可作为“有界数据缓冲区”,生产者插入数据到队列容器中,并由消费者提取。ArrayBlockingQueue一旦创建,容量不能改变。

当队列容量满时,尝试将元素放入队列将导致操作阻塞;尝试从一个空队列中取一个元素也会同样阻塞。

ArrayBlockingQueue默认情况下不能保证线程访问队列的公平性,所谓公平性是指严格按照线程等待的绝对时间顺序,即最先等待的线程能够最先访问到ArrayBlockingQueue。而非公平性则是指访问ArrayBlockingQueue的顺序不是遵守严格的时间顺序,有可能存在,一旦ArrayBlockingQueue可以被访问时,长时间阻塞的线程依然无法访问到ArrayBlockingQueue。如果保证公平性,通常会降低吞吐量。如果需要获得公平性的ArrayBlockingQueue,可采用如下代码:

  1. private static ArrayBlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(10,true);

2.LinkedBlockingQueue
LinkedBlockingQueue是用链表实现的有界阻塞队列,同样满足FIFO的特性,与ArrayBlockingQueue相比起来具有更高的吞吐量,为了防止LinkedBlockingQueue容量迅速增,损耗大量内存。通常在创建LinkedBlockingQueue对象时,会指定其大小,如果未指定,容量等于Integer.MAX_VALUE

3.PriorityBlockingQueue
PriorityBlockingQueue是一个支持优先级的无界阻塞队列。默认情况下元素采用自然顺序进行排序,也可以通过自定义类实现compareTo()方法来指定元素排序规则,或者初始化时通过构造器参数Comparator来指定排序规则。

4.SynchronousQueue
SynchronousQueue每个插入操作必须等待另一个线程进行相应的删除操作,因此,SynchronousQueue实际上没有存储任何数据元素,因为只有线程在删除数据时,其他线程才能插入数据,同样的,如果当前有线程在插入数据时,线程才能删除数据。SynchronousQueue也可以通过构造器参数来为其指定公平性。

5.LinkedTransferQueue
LinkedTransferQueue是一个由链表数据结构构成的无界阻塞队列,由于该队列实现了TransferQueue接口,与其他阻塞队列相比主要有以下不同的方法:
TransferQueue ;生产者会一直阻塞直到所添加到队列的元素被某一个消费者所消费(不仅仅是添加到队列里就完事)。
transfer(E e) 如果当前有线程(消费者)正在调用take()方法或者可延时的poll()方法进行消费数据时,生产者线程可以调用transfer方法将数据传递给消费者线程。如果当前没有消费者线程的话,生产者线程就会将数据插入到队尾,直到有消费者能够进行消费才能退出;
tryTransfer(E e) tryTransfer方法如果当前有消费者线程(调用take方法或者具有超时特性的poll方法)正在消费数据的话,该方法可以将数据立即传送给消费者线程,如果当前没有消费者线程消费数据的话,就立即返回false。因此,与transfer方法相比,transfer方法是必须等到有消费者线程消费数据时,生产者线程才能够返回。而tryTransfer方法能够立即返回结果退出。
tryTransfer(E e,long timeout,imeUnit unit) 与transfer基本功能一样,只是增加了超时特性,如果数据才规定的超时时间内没有消费者进行消费的话,就返回false。

6.LinkedBlockingDeque
LinkedBlockingDeque是基于链表数据结构的有界阻塞双端队列,如果在创建对象时为指定大小时,其默认大小为Integer.MAX_VALUE。与LinkedBlockingQueue相比,主要的不同点在于,LinkedBlockingDeque具有双端队列的特性。
clipboard401.png
LinkedBlockingDeque的基本操作可以分为四种类型:1.特殊情况,抛出异常;2.特殊情况,返回特殊值如null或者false;3.当线程不满足操作条件时,线程会被阻塞直至条件满足;4. 操作具有超时特性。
另外,LinkedBlockingDeque实现了BlockingDueue接口而LinkedBlockingQueue实现的是BlockingQueue,,两个接口的功能是可以等价使用的,比如BlockingQueue的add方法和BlockingDeque的addLast方法的功能是一样的。

7.DelayQueue
DelayQueue是一个存放实现Delayed接口的数据的无界阻塞队列,只有当数据对象的延时时间达到时才能插入到队列进行存储。如果当前所有的数据都还没有达到创建时所指定的延时期,则队列没有队头,并且线程通过poll等方法获取数据元素则返回null。所谓数据延时期满时,则是通过Delayed接口的getDelay(TimeUnit.NANOSECONDS)来进行判定,如果该方法返回的是小于等于0则说明该数据元素的延时期已满。

总结 :上面列出了七个阻塞队列,其实从类名就可以大致判断出这个类的特性与其实现的数据结构,需要注意的是队列有界和无界的问题, 有界的队列有:ArrayBlockingQueue,LinkedBlockingQueue,LinkedBlockingDeque;
无界的队列有:PriorityBlockingQueue,LinkedTransferQueue ,DelayQueue;
还有一个特殊的SynchronousQueue,它实际上没有大小,因为从它的功能可以看出,每个插入操作必须等待另一个线程进行相应的删除操作,所以内部没有数据。 实现原理还是基于CAS操作的。

三:ArrayBlockingQueue分析:

1: 实现原理,本篇开头已经提到过了,为了实现插入与获取的阻塞操作,ArrayBlockingQueue其实就是使用了Lock中的Condition的等待通知机制。 所以在生产者与消费者模式中,可以直接使用ArrayBlockingQueue实现。 下面来分析源码:
2:
2.1:主要属性;

  1. /** The queued items */
  2. final Object[] items;
  3. /** items index for next take, poll, peek or remove */
  4. int takeIndex;
  5. /** items index for next put, offer, or add */
  6. int putIndex;
  7. /** Number of elements in the queue */
  8. int count;
  9. /*
  10. * Concurrency control uses the classic two-condition algorithm
  11. * found in any textbook.
  12. */
  13. 重点关注这三个
  14. /** Main lock guarding all access */
  15. final ReentrantLock lock;
  16. /** Condition for waiting takes */
  17. private final Condition notEmpty;
  18. /** Condition for waiting puts */
  19. private final Condition notFull;
  20. /**
  21. * Shared state for currently active iterators, or null if there
  22. * are known not to be any. Allows queue operations to update
  23. * iterator state.
  24. */
  25. transient Itrs itrs = null;

从源码中可以看出ArrayBlockingQueue内部是采用数组进行数据存储的(属性items),为了保证线程安全,采用的是ReentrantLock lock,为了保证可阻塞式的插入删除数据利用的是Condition,当获取数据的消费者线程被阻塞时会将该线程放置到notEmpty等待队列中,当插入数据的生产者线程被阻塞时,会将该线程放置到notFull等待队列中。而notEmpty和notFull等中要属性在构造方法中进行创建:

  1. public ArrayBlockingQueue(int capacity, boolean fair) {
  2. if (capacity <= 0)
  3. throw new IllegalArgumentException();
  4. this.items = new Object[capacity];
  5. lock = new ReentrantLock(fair);
  6. notEmpty = lock.newCondition();
  7. notFull = lock.newCondition();
  8. }

2.2:put方法详解:

  1. public void put(E e) throws InterruptedException {
  2. checkNotNull(e);
  3. final ReentrantLock lock = this.lock;
  4. lock.lockInterruptibly();
  5. try {
  6. //数组满了就等待
  7. while (count == items.length)
  8. notFull.await();
  9. enqueue(e);
  10. } finally {
  11. lock.unlock();
  12. }
  13. }

可以看到,内部就是和等待通知机制,当队列已满时(count == items.length)将线程移入到notFull等待队列中,如果当前满足插入数据的条件,就可以直接调用enqueue(e)插入数据元素。
注意一点的是,唤醒其他添加操作的阻塞线程的操作在enqueue方法中。

  1. rivate void enqueue(E x) {
  2. // assert lock.getHoldCount() == 1;
  3. // assert items[putIndex] == null;
  4. final Object[] items = this.items;
  5. items[putIndex] = x;
  6. if (++putIndex == items.length)
  7. putIndex = 0;
  8. count++;
  9. //此处使用了signal而没有使用signalAll(),原因在下:
  10. notEmpty.signal();
  11. }

因为ArrayBlockingQueue中,生产者put与消费者take 采用的是两个等待队列,唤醒操作是独立的, 上述代码中是notFull的等待队列被唤醒后执行到enqueue中,使用noempty进行通知消费者线程。 所以不存在生产者唤醒生产者的情况,用signal没问题。
2.3:take方法详解:

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
            //消费者阻塞,即将消费者移入等待队列
            notEmpty.await();
            //获取数据
        return dequeue();
    } finally {
        lock.unlock();
    }
}

take方法也主要做了两步:1. 如果当前队列为空的话,则将获取数据的消费者线程移入到等待队列中;2. 若队列不为空则获取数据,即完成出队操作dequeue。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;
}

dequeue方法也主要做了两件事情:1. 获取队列中的数据,即获取数组中的数据元素((E) items[takeIndex]);2. 通知notFull等待队列中的线程,使其由等待队列移入到同步队列中,使其能够有机会获得lock,并执行完成功退出。
通过上面的分析,ArrayBlockingQueue的内部阻塞机制就已经分析完了,原理就是基于Condition机制,但是它使用了两个Condition对象,相当于创建了两个等待队列,生产者与消费者等待时分别加入这两个等待队列中,在通知时,这两个等待队列中的线程节点是相互被唤醒的,所以不存在唤醒同类线程的问题, 这种设计很值得学习,这样就不用每次唤醒时通过singalAll唤醒全部的线程了。

看完了ArrayBlockingQueue,接下来看LinkedBlockingQueue:

四:LinkedBlockingQueue:

LinkedBlockingQueue是用链表实现的有界阻塞队列,当构造对象时为指定队列大小时,队列默认大小为Integer.MAX_VALUE。从它的构造方法可以看出:

public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);
}

3.1 LinkedBlockingQueue的主要属性

/** Current number of elements */
private final AtomicInteger count = new AtomicInteger();

/**
 * Head of linked list.
 * Invariant: head.item == null
 */
transient Node<E> head;

/**
 * Tail of linked list.
 * Invariant: last.next == null
 */
private transient Node<E> last;


/** Lock held by take, poll, etc */
private final ReentrantLock takeLock = new ReentrantLock();

/** Wait queue for waiting takes */
private final Condition notEmpty = takeLock.newCondition();

/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();

/** Wait queue for waiting puts */
private final Condition notFull = putLock.newCondition();

可以看出与ArrayBlockingQueue不同的是:LinkedBlockingQueue采用的是两个lock对象来维护put操作线程和take操作的线程, 即可以想到,生产者和消费者的线程节点是分别在两个同步队列中的。
因此,也由这两个lock生成了两个对应的condition(notEmpty和notFull)来实现可阻塞的插入和删除数据。并且,采用了链表的数据结构来实现队列,Node结点的定义为:

static class Node<E> {
    E item;

    /**
     * One of:
     * - the real successor Node
     * - this Node, meaning the successor is head.next
     * - null, meaning there is no successor (this is the last node)
     */
    Node<E> next;

    Node(E x) { item = x; }
}

3.2 put操作:

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    // Note: convention in all put/take/etc is to preset local var
    // holding count negative to indicate failure unless set.
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count; //
    putLock.lockInterruptibly();
    try {
        /*
         * Note that count is used in wait guard even though it is
         * not protected by lock. This works because count can
         * only decrease at this point (all other puts are shut
         * out by lock), and we (or some other waiting put) are
         * signalled if it ever changes from capacity. Similarly
         * for all other uses of count in other wait guards.
         */
         //如果队列已满,则阻塞当前线程,将其移入等待队列
        while (count.get() == capacity) {
            notFull.await();
        }
        //入队列操作,插入数据
        enqueue(node);
        //获取容量的大小
        c = count.getAndIncrement();
        //若队列满足插入数据的条件,则通知被阻塞的生产者线程
        if (c + 1 < capacity)
            //通知继续生产
            notFull.signal();
    } finally {
        putLock.unlock();
    }
    if (c == 0) //当c==0,即最大值溢出后,结果为0
        //通知被阻塞的消费者线程进行消费
        signalNotEmpty();
}
private void signalNotEmpty() {
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();
    try {
        //通知消费
        notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
}

可以发现,put操作的生产是根据目前容量count(原子类对象)与capacity的比较判断的,如果count的值等于capacity时,就等待陷入阻塞, 小于就通知其他被阻塞的生产者线程生产。 这里需要注意的是这个c,c是count自增后获取的,如果c溢出后值变为了0,证明容器容量已满, 就可以通知消费者线程进行消费。

再来看take操作:

public E take() throws InterruptedException {
    E x;
    int c = -1;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly(); //如果有interrupt调用,则可以中断
    try {
        while (count.get() == 0) {
            notEmpty.await();   //如果队列为空,就阻塞消费者线程
        }
        x = dequeue();       //出队
        c = count.getAndDecrement();
        if (c > 1)
            notEmpty.signal();  //通知唤醒消费者消费
    } finally {
        takeLock.unlock();
    }
    //c的值为capacity,证明已经消费了capacity个,消费完了,需要通知生产了。
    if (c == capacity)
        signalNotFull();
    return x;
}

private void signalNotFull() {
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        notFull.signal();
    } finally {
        putLock.unlock();
    }
}

take操作与put操作的原理是一样的,只不过是相反的,看注释就能理解。

到这,LinkedBlockingQueue就分析完了,下面与ArrayBlockingQueue做一个对比:

同样都是基于Condition的生产者与消费者模式实现的,但是它们两个的实现手段有所不同:

1:ArrayBlockingQueue,采用数组,需要自定义大小,它是通过利用一个lock对象生成两个Condition对象notFull与notEmpty, 本质是一个同步队列维护了两个等待队列,两个等待队列中的节点可以相互被通知唤醒,这样设计也避免了可能唤醒同类线程的问题。

2:LinkedBlockingQueue,采用链表,容量为Integer的最大值,它是使用了两个lock对象,每个lock对象又维护一个Condition对象,相当于一个生产锁与消费锁, 但是生产锁与消费锁又怎么样联系在一起呢,可以想到synchronized锁是锁的对象, 而该类中就有一个原子类对象count, 所以把这两个锁联系在一起的就是这个count对象,根据这个count对象的大小来进行生产或者消费的调度,至于具体的逻辑已经在put,take方法中解释了。
LinkedBlockingQueue的设计可以降低线程由于线程无法获取到lock而进入WAITING状态的可能性,从而提高了线程并发执行的效率。