jdk-BlockingQueue源码学习

上文:jdk-ReentrantLock&AQS源码阅读

源码下载:https://gitee.com/hong99/jdk8


BlockingQueue介绍

9739bedd4f911d0829d093ed19c7e7c2.png

    BlockingQueue是一个FIFO阻塞(Blocking)队列,支持为空时阻塞等待队列中有元素再返回,也支持新增元素时,队列若已满,阻塞等待队列有新空间再放入。所在位置:java.util.concurrent.BlockingQueue,是AQS中的队列实现,其中基于BlockingQueue 实现的队列有BlockingDeque、TransferQueue、LinkedBlockingDeque、LinkedBlockingQueue等,如上图。

    BlockingQueue是一个接口类,继承Queue 相关的方法说明如下:

java.util.concurrent.BlockingQueue

方法名称

说明

备注

add(E e)

扫描二维码关注公众号,回复: 15400069 查看本文章

添加方法


offer(E e)

添加方法


remove()

移除方法


poll()

移除方法


element()

检查方法


peek()

检查方法


put(E e)

添加方法

会阻塞

take()

移除方法


下面看看各个子类实现的逻辑。

注意:由于这个是AQS里面的一部分,所以看到源码中的lock基本都是ReentrantLock所以,说明不会再细讲。

四种由BlockingQueue实现的阻塞队列

  • ArrayBlockingQueue 由数组支持的有界队列

  • LinkedBlockingQueue 由链接节点支持的可选有界队列

  • PriorityBlockingQueue 由优先级堆支持的无界优先级队列

  • LinkedBlockingDeque(BlockingDeque) 由优先级堆支持的、基于时间的调度队列

基本的使用

//由数组支持的有界队列
BlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(16);
for (int i = 0; i < 100; i++) {
    //超过容量会爆出异常
    arrayBlockingQueue.add("第"+i);
}

结果

Exception in thread "main" java.lang.IllegalStateException: Queue full
  at java.util.AbstractQueue.add(AbstractQueue.java:98)
  at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:312)
  at com.aqs.BlockingQueueTest.main(BlockingQueueTest.java:16)
//由数组支持的有界队列
BlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(16);
for (int i = 0; i < 100; i++) {
    //超过容量会爆出异常
    //arrayBlockingQueue.add("第"+i);
    //超过容量会阻塞
    arrayBlockingQueue.put("第"+i);
    //超过容量会返回false
    //System.out.println(arrayBlockingQueue.offer("第"+i));
}

结果:阻塞了

a9212501d106f59e02bcabcd34a794fa.png

//由数组支持的有界队列
BlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(16);
for (int i = 0; i < 100; i++) {
    //超过容量会爆出异常
    //arrayBlockingQueue.add("第"+i);
    //超过容量会阻塞
    //arrayBlockingQueue.put("第"+i);
    //超过容量会返回false
    System.out.println(arrayBlockingQueue.offer("第"+i));
}

结果

true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false

其他测试

public class BlockingQueueTest {

    public static void main(String[] args) throws Exception {
        //由数组支持的有界队列
// BlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(16);
// for (int i = 0; i < 100; i++) {
// //超过容量会爆出异常
// //arrayBlockingQueue.add("第"+i);
// //超过容量会阻塞
// //arrayBlockingQueue.put("第"+i);
// //超过容量会返回false
// //System.out.println(arrayBlockingQueue.offer("第"+i));
// //带过期时间
// arrayBlockingQueue.offer("第"+i,1000,TimeUnit.SECONDS);
// }
        //由链接节点支持的可选有界队列
        BlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<>();
// for (int i = 0; i < 100; i++) {
            //超过容量会爆出异常
            //linkedBlockingQueue.add("第"+i);
            //超过容量会阻塞
            //linkedBlockingQueue.put("第"+i);
            //超过容量会返回false
            //System.out.println(linkedBlockingQueue.offer("第"+i));
            //带过期时间
            //linkedBlockingQueue.offer("第"+i,1000,TimeUnit.SECONDS);
// }
        //由优先级堆支持的无界优先级队列
        BlockingQueue<String> priorityBlockingQueue =new PriorityBlockingQueue();
        for (int i = 0; i < 1000; i++) {
            //超过容量会爆出异常
            //priorityBlockingQueue.add("第"+i);
            //超过容量会阻塞
            //priorityBlockingQueue.put("第"+i);
            //超过容量会返回false
            System.out.println(priorityBlockingQueue.offer("第"+i));
            //带过期时间
            //priorityBlockingQueue.offer("第"+i,1000,TimeUnit.SECONDS);
        }
        System.out.println(priorityBlockingQueue.take());
        System.out.println(priorityBlockingQueue.remainingCapacity());
        System.out.println(priorityBlockingQueue.remove());
        System.out.println(priorityBlockingQueue.poll());
//
// //由优先级堆支持的、基于时间的调度队列
// BlockingQueue<String> delayQueue = new DelayQueue();
// for (int i = 0; i < 100; i++) {
// //超过容量会爆出异常
// delayQueue.add("第"+i);
// //超过容量会阻塞
// //delayQueue.put("第"+i);
// //超过容量会返回false
// //System.out.println(arrayBlockingQueue.offer("第"+i));
// //带过期时间
// //priorityBlockingQueue.offer("第"+i,1000,TimeUnit.SECONDS);
// }
    }
}

源码学习

java.util.AbstractQueue 的源码实现,作为Queue的最基础实现,本身也是抽象供具体队列实现。

package java.util;

public abstract class AbstractQueue<E>
    extends AbstractCollection<E>
    implements Queue<E> {

    //供子类使用的构造函数
    protected AbstractQueue() {
    }

    //添加方法,如果不成功跑出异常
    public boolean add(E e) {
        //offer由子类实现
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

    //删除方法,如果不成功抛出异常
    public E remove() {
        //poll由子类实现
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

    //获取一个对象,如果为空抛出异常
    public E element() {
        //由子类实现
        E x = peek();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

    //清空队列
    public void clear() {
        while (poll() != null)
            ;
    }

    //添加列表到队列中
    public boolean addAll(Collection<? extends E> c) {
        //为空抛出异常
        if (c == null)
            throw new NullPointerException();
        //等于当前对象抛出异pkh
        if (c == this)
            throw new IllegalArgumentException();
        boolean modified = false;
        //循环添加
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }

}

java.util.concurrent.ArrayBlockingQueue 的源码实现

966e92806ee6cd0160377781d25c34e4.png

介绍一下:ArrayBlockingQueue 是一个阻塞队列,底层用的是数组结构实现,也是先进先出的顺序,并且是一个线程安全的集合,底层是通过ReentranLock来实现,唯一的注意是这个队列的容量一定初始化就确定了,所以在使用的时候要特别注意。

131827ef67e2ab163506a250ef1a88c7.png

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;

    /*
     * Concurrency control uses the classic two-condition algorithm
     * found in any textbook.
     */

    /** 这里使用重入锁保证线程安全 */
    final ReentrantLock lock;

    /** 用于控制take()里是否让线程等待 */
    private final Condition notEmpty;

    /** 用于控制put()时已满是否等待 */
    private final Condition notFull;

    //迭代器(用于处理复杂的 添加 删除 或多线程情况)
    transient Itrs itrs = null;

    // Internal helper methods

    /**
     * Circularly decrement i.
     */
     //获取下标-1
    final int dec(int i) {
        //如果为0那么就是数组-1 ,如果不是则是传进来的i-1
        return ((i == 0) ? items.length : i) - 1;
    }

    //获取指定下标的元素
    @SuppressWarnings("unchecked")
    final E itemAt(int i) {
        return (E) items[i];
    }

    //检查参数是否为空,如果为空抛出NullPointerException
    private static void checkNotNull(Object v) {
        if (v == null)
            throw new NullPointerException();
    }

    //新插入元素
    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        //如果与数组长度相同,那么下标置0
        if (++putIndex == items.length)
            putIndex = 0;
        //排队列+1
        count++;
        //唤醒一个等待线程
        notEmpty.signal();
    }

    //获取
    private E dequeue() {
        //获取列表
        final Object[] items = this.items;
        //获取最后一个元素
        E x = (E) items[takeIndex];
        //数组坐标赋为空
        items[takeIndex] = null;
        //判断自增后的长度等于队列长度
        if (++takeIndex == items.length)
            //坐标置为0
            takeIndex = 0;
        //队列长度减1
        count--;
        //迭代器不为空
        if (itrs != null)
            //出队列调用判断是否为空或首位删除过期的迭代器并通知所有迭代器
            itrs.elementDequeued();
        //唤醒notFull中的一个线程
        notFull.signal();
        //返回该元gxix
        return x;
    }

    /**
     * Deletes item at array index removeIndex.
     * Utility for remove(Object) and iterator.remove.
     * Call only when holding lock.
     */
     //无返回的删除指定位置的队列数据
    void removeAt(final int removeIndex) {
        //获取数组
        final Object[] items = this.items;
        //如果删除的位置等于最后一个坐标
        if (removeIndex == takeIndex) {
            // removing front item; just advance
            //直接将坐标赋空
            items[takeIndex] = null;
            //同上处理
            if (++takeIndex == items.length)
                takeIndex = 0;
            //数组减1
            count--;
            if (itrs != null)
                //出队列调用判断是否为空或首位删除过期的迭代器并通知所有迭代器
                itrs.elementDequeued();
        } else {
            //如果等于添加的坐标
            final int putIndex = this.putIndex;
            //空循环 条件是找到时位置赋空时退出
            for (int i = removeIndex;;) {
                int next = i + 1;
                //如果等于长度那么 next赋0
                if (next == items.length)
                    next = 0;
                 //如果不等于下一个坐标
                if (next != putIndex) {
                    //向前移一位
                    items[i] = items[next];
                    i = next;
                } else {
                    //如果等于 putIndex 那么 将这个位置置空 然后putIndex等于i 退出
                    items[i] = null;
                    this.putIndex = i;
                    break;
                }
            }
            //队列减1
            count--;
            //迭代器不为空 进行删除通知
            if (itrs != null)
                itrs.removedAt(removeIndex);
        }
        //唤醒notFull中的一个线程
        notFull.signal();
    }

    //初始化指定容量的阻塞队列(非公平锁)
    public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }

    //初始化指定容量的阻塞队列,并且可指定是否为公平锁 true为是 false为否
    public ArrayBlockingQueue(int capacity, boolean fair) {
        //容量小于等于零抛出异常
        if (capacity <= 0)
            throw new IllegalArgumentException();
        //初始化数组容量
        this.items = new Object[capacity];
        //创建重载锁
        lock = new ReentrantLock(fair);
        //初始化notEmpty和notFull
        notEmpty = lock.newCondition();
        notFull = lock.newCondition();
    }

    //capacity 初始化容量
    //fair true为公平锁 false为非公平
    //c 实始数组
    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();
            }
            //循环后的i总数
            count = i;
            //获取下一个添加的下标
            putIndex = (i == capacity) ? 0 : i;
        } finally {
            //解锁
            lock.unlock();
        }
    }

    //添加一个元素到队列尾位 如果队列已满抛出异常
    public boolean add(E e) {
        return super.add(e);
    }

    //添加一个元素到队列尾部,如果队列已满
    public boolean offer(E e) {
        //检查为空抛出异常
        checkNotNull(e);
        //获取得入锁
        final ReentrantLock lock = this.lock;
        //上锁
        lock.lock();
        try {
            //如果长度等于队列长度了那么返回false
            if (count == items.length)
                return false;
            else {
                //入队
                enqueue(e);
                //返回成功
                return true;
            }
        } finally {
            //解锁
            lock.unlock();
        }
    }

    //添加方法
    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();
        }
    }

    //将元素插到尾部,如果队列已满则指定过期时间,直时直接返回false
    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) {
                //超过等待时间直接返回false
                if (nanos <= 0)
                    return false;
                //获取最新纳秒
                nanos = notFull.awaitNanos(nanos);
            }
            //入队
            enqueue(e);
            //返顺成功
            return true;
        } finally {
            //解锁
            lock.unlock();
        }
    }
    //获取一个元素
    public E poll() {
        //获取重入锁
        final ReentrantLock lock = this.lock;
        //上锁
        lock.lock();
        try {
            //如果为0返回null 不为0返回一个队头元素(FIFO)
            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();
        }
    }
    //
    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            //返回一个元素
            return itemAt(takeIndex); // null when queue is empty
        } finally {
            lock.unlock();
        }
    }

    //获取队列数量(带锁的)
    public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }

   //返回此队列当前剩余的容量(带锁)
    public int remainingCapacity() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return items.length - count;
        } finally {
            lock.unlock();
        }
    }

    //从队列移除与对象相同的元素
    public boolean remove(Object o) {
        //为空直接返回false
        if (o == null) return false;
        //获取队列
        final Object[] items = this.items;
        //获取重入锁
        final ReentrantLock lock = this.lock;
        //上锁
        lock.lock();
        try {
            //如果有值
            if (count > 0) {
                //获取最后一个坐标
                final int putIndex = this.putIndex;
                //获取上一个坐标
                int i = takeIndex;
                do {
                    //如果相同 则移除并返回 没有一出一直循环
                    if (o.equals(items[i])) {
                        removeAt(i);
                        return true;
                    }
                    if (++i == items.length)
                        i = 0;
                } while (i != putIndex);
            }
            //没找着返回false
            return false;
        } finally {
            //解锁
            lock.unlock();
        }
    }

    /**
     * Returns {@code true} if this queue contains the specified element.
     * More formally, returns {@code true} if and only if this queue contains
     * at least one element {@code e} such that {@code o.equals(e)}.
     *
     * @param o object to be checked for containment in this queue
     * @return {@code true} if this queue contains the specified element
     */
     //判断是否包含这个元素(带锁)
    public boolean contains(Object o) {
        //为空直接返回false
        if (o == null) return false;
        //获取列表
        final Object[] items = this.items;
        //获取重入锁
        final ReentrantLock lock = this.lock;
        //上锁
        lock.lock();
        try {
            //判断队列长度大于0
            if (count > 0) {
                //获取最后一个位置索引
                final int putIndex = this.putIndex;
                //获取上一个添加的索此
                int i = takeIndex;
                do {
                    //判断是否一致 如果是返回true
                    if (o.equals(items[i]))
                        return true;
                     //自增长度相等则i为0
                    if (++i == items.length)
                        i = 0;
                        //循环 条件 i为等于最后一个元素
                } while (i != putIndex);
            }
            //都没找着返回false
            return false;
        } finally {
            //解锁
            lock.unlock();
        }
    }

    //将队列内容转成数组
    public Object[] toArray() {
        //初始化返回对象
        Object[] a;
           //获取重入锁
        final ReentrantLock lock = this.lock;
        //上锁
        lock.lock();
        try {
            //获取队列长度
            final int count = this.count;
            //实始化a数组长茺为队列长度
            a = new Object[count];
            //获取长度数量
            int n = items.length - takeIndex;
            if (count <= n)
                //系统拷贝 全部
                System.arraycopy(items, takeIndex, a, 0, count);
            else {
                //系统拷贝 总长度为n
                System.arraycopy(items, takeIndex, a, 0, n);
                System.arraycopy(items, 0, a, n, count - n);
            }
        } finally {
            //解锁
            lock.unlock();
        }
        return a;
    }
    //将列表转成数组
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        final Object[] items = this.items;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            final int count = this.count;
            final int len = a.length;
            if (len < count)
                //长度小于len 那么进行反射复制(底层是新创建数据可以深入研分)
                a = (T[])java.lang.reflect.Array.newInstance(
                    a.getClass().getComponentType(), count);
            int n = items.length - takeIndex;
            if (count <= n)
                System.arraycopy(items, takeIndex, a, 0, count);
            else {
                System.arraycopy(items, takeIndex, a, 0, n);
                System.arraycopy(items, 0, a, n, count - n);
            }
            if (len > count)
                a[count] = null;
        } finally {
            lock.unlock();
        }
        return a;
    }
    //tostring方法(带锁)
    public String toString() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int k = count;
            if (k == 0)
                return "[]";

            final Object[] items = this.items;
            StringBuilder sb = new StringBuilder();
            sb.append('[');
            for (int i = takeIndex; ; ) {
                Object e = items[i];
                sb.append(e == this ? "(this Collection)" : e);
                if (--k == 0)
                    return sb.append(']').toString();
                sb.append(',').append(' ');
                if (++i == items.length)
                    i = 0;
            }
        } finally {
            lock.unlock();
        }
    }

    //清空队列
    public void clear() {
        //获取队列信息
        final Object[] items = this.items;
        //上锁
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            //处理掉内容 并将迭代器也清空 还有初始化count takeIndex (这里感觉直接清就行了,为啥还要循环)
            int k = count;
            if (k > 0) {
                final int putIndex = this.putIndex;
                int i = takeIndex;
                do {
                    items[i] = null;
                    if (++i == items.length)
                        i = 0;
                } while (i != putIndex);
                takeIndex = putIndex;
                count = 0;
                if (itrs != null)
                    itrs.queueIsEmpty();
                for (; k > 0 && lock.hasWaiters(notFull); k--)
                    notFull.signal();
            }
        } finally {
            lock.unlock();
        }
    }

    //从集合中删除指定队列的无素
    public int drainTo(Collection<? super E> c) {
        //看下面方法
        return drainTo(c, Integer.MAX_VALUE);
    }

   // c为元素列表 maxElements最大值
    public int drainTo(Collection<? super E> c, int maxElements) {
        checkNotNull(c);
        if (c == this)
            throw new IllegalArgumentException();
         //小于0返回0
        if (maxElements <= 0)
            return 0;
        final Object[] items = this.items;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            //取最小值
            int n = Math.min(maxElements, count);
            int take = takeIndex;
            int i = 0;
            try {
                //循环移除
                while (i < n) {
                    @SuppressWarnings("unchecked")
                    E x = (E) items[take];
                    c.add(x);
                    items[take] = null;
                    if (++take == items.length)
                        take = 0;
                    i++;
                }
                return n;
            } finally {
                // Restore invariants even if c.add() threw
                if (i > 0) {
                    count -= i;
                    takeIndex = take;
                    if (itrs != null) {
                        if (count == 0)
                            itrs.queueIsEmpty();
                        else if (i > take)
                            itrs.takeIndexWrapped();
                    }
                    for (; i > 0 && lock.hasWaiters(notFull); i--)
                        notFull.signal();
                }
            }
        } finally {
            lock.unlock();
        }
    }

   //获取新迭代器
    public Iterator<E> iterator() {
        return new Itr();
    }

   //迭代类
    class Itrs {

        /**
         * Node in a linked list of weak iterator references.
         */
        private class Node extends WeakReference<Itr> {
            //下一个节点
            Node next;
            //构建实现
            Node(Itr iterator, Node next) {
                //初始化
                super(iterator);
                //初始化next
                this.next = next;
            }
        }

        //自增
        int cycles = 0;

        //头节点
        private Node head;

        //删除的迭代器
        private Node sweeper = null;

        private static final int SHORT_SWEEP_PROBES = 4;
        private static final int LONG_SWEEP_PROBES = 16;
        //构建方法
        Itrs(Itr initial) {
            //初始容量
            register(initial);
        }

        //删除旧迭代器
        void doSomeSweeping(boolean tryHarder) {
            // assert lock.getHoldCount() == 1;
            // assert head != null;
            //true为16否则为4
            int probes = tryHarder ? LONG_SWEEP_PROBES : SHORT_SWEEP_PROBES;
            //节点
            Node o, p;
            //获取删除迭代器
            final Node sweeper = this.sweeper;
            //限制一次性扫描条件
            boolean passedGo; // to limit search to one full sweep
            //为空 o 和p 都置空
            if (sweeper == null) {
                o = null;
                p = head;
                passedGo = true;
            } else {
                //删除迭代器
                o = sweeper;
                //下一个节点
                p = o.next;
                //标记
                passedGo = false;
            }
            //循环递减
            for (; probes > 0; probes--) {
                //如果p为空 判断是否标记过如果是退出 如果否则o 为空 p为头节点
                if (p == null) {
                    if (passedGo)
                        break;
                    o = null;
                    p = head;
                    passedGo = true;
                }
                //获取迭代器
                final Itr it = p.get();
                //获取下节点
                final Node next = p.next;
                //如果为空 或 下一个节点小于0 直接做清空操作
                if (it == null || it.isDetached()) {
                    // found a discarded/exhausted iterator
                    probes = LONG_SWEEP_PROBES; // "try harder"
                    // unlink p
                    p.clear();
                    p.next = null;
                    if (o == null) {
                        head = next;
                        if (next == null) {
                            // We've run out of iterators to track; retire
                            itrs = null;
                            return;
                        }
                    }
                    else
                        o.next = next;
                } else {
                    o = p;
                }
                p = next;
            }

            this.sweeper = (p == null) ? null : o;
        }

        //注册 创建头节点
        void register(Itr itr) {
            // assert lock.getHoldCount() == 1;
            head = new Node(itr, head);
        }

        //
        void takeIndexWrapped() {
            // assert lock.getHoldCount() == 1;
            //++1
            cycles++;
            //循环赋为空,直到p不为null
            for (Node o = null, p = head; p != null;) {
                final Itr it = p.get();
                final Node next = p.next;
                if (it == null || it.takeIndexWrapped()) {
                    // unlink p
                    // assert it == null || it.isDetached();
                    p.clear();
                    p.next = null;
                    if (o == null)
                        head = next;
                    else
                        o.next = next;
                } else {
                    o = p;
                }
                p = next;
            }
            //头不为空
            if (head == null) // no more iterators to track
                itrs = null;
        }

        //每当删除时,调用 并且通知所有迭代器
        void removedAt(int removedIndex) {
            for (Node o = null, p = head; p != null;) {
                final Itr it = p.get();
                final Node next = p.next;
                if (it == null || it.removedAt(removedIndex)) {
                    // unlink p
                    // assert it == null || it.isDetached();
                    p.clear();
                    p.next = null;
                    if (o == null)
                        head = next;
                    else
                        o.next = next;
                } else {
                    o = p;
                }
                p = next;
            }
            if (head == null) // no more iterators to track
                itrs = null;
        }

       //当队列为空时调用
        void queueIsEmpty() {
            // assert lock.getHoldCount() == 1;
            //清空数据
            for (Node p = head; p != null; p = p.next) {
                Itr it = p.get();
                if (it != null) {
                    p.clear();
                    it.shutdown();
                }
            }
            head = null;
            itrs = null;
        }

        //每当元素退出时调用
        void elementDequeued() {
            // assert lock.getHoldCount() == 1;
            if (count == 0)
                //清空队列数据
                queueIsEmpty();
            else if (takeIndex == 0)
                takeIndexWrapped();
        }
    }

    //私有的迭代类 实现
    private class Itr implements Iterator<E> {
        /** Index to look for new nextItem; NONE at end */
        //获取下一个元素的索引
        private int cursor;

        //下一个元素
        private E nextItem;

        //下一个元素索引
        private int nextIndex;

        //最后一个元素
        private E lastItem;

        //最后一个元素索引
        private int lastRet;

        //上一个元素索引
        private int prevTakeIndex;

        //以前值的循环索引
        private int prevCycles;
        //代表未定义
        private static final int NONE = -1;

       //代表已删除
        private static final int REMOVED = -2;
        //分离模式
        private static final int DETACHED = -3;

        Itr() {
            // assert lock.getHoldCount() == 0;
            lastRet = NONE;
            //获取锁
            final ReentrantLock lock = ArrayBlockingQueue.this.lock;
            //上锁
            lock.lock();
            try {
                //如果为0直接清空
                if (count == 0) {
                    // assert itrs == null;
                    cursor = NONE;
                    nextIndex = NONE;
                    prevTakeIndex = DETACHED;
                } else {
                    //获取上一个坐标
                    final int takeIndex = ArrayBlockingQueue.this.takeIndex;
                    prevTakeIndex = takeIndex;
                    //获取元素
                    nextItem = itemAt(nextIndex = takeIndex);
                    //清空指定对象
                    cursor = incCursor(takeIndex);
                    //为空新=建一个
                    if (itrs == null) {
                        itrs = new Itrs(this);
                    } else {
                        //新增加迭代器
                        itrs.register(this); // in this order
                        //删除旧迭代器
                        itrs.doSomeSweeping(false);
                    }
                    prevCycles = itrs.cycles;
                    // assert takeIndex >= 0;
                    // assert prevTakeIndex == takeIndex;
                    // assert nextIndex >= 0;
                    // assert nextItem != null;
                }
            } finally {
                //解锁
                lock.unlock();
            }
        }
        //判断是否存在先前值
        boolean isDetached() {
            // assert lock.getHoldCount() == 1;
            return prevTakeIndex < 0;
        }
        //获取自增偏移量
        private int incCursor(int index) {
            // assert lock.getHoldCount() == 1;
            //与长度相同为0
            if (++index == items.length)
                index = 0;
            //如果为添加节点 那么返回-1
            if (index == putIndex)
                index = NONE;
            //返回自增后的值
            return index;
        }


        //返回 是否大于队列数 ,如果小于返回false
        private boolean invalidated(int index, int prevTakeIndex,
                                    long dequeues, int length) {
            if (index < 0)
                return false;
            int distance = index - prevTakeIndex;
            if (distance < 0)
                distance += length;
            return dequeues > distance;
        }

        //删除或更新的时候通知后的处理
        private void incorporateDequeues() {
            // assert lock.getHoldCount() == 1;
            // assert itrs != null;
            // assert !isDetached();
            // assert count > 0;
            //获取
            final int cycles = itrs.cycles;
            final int takeIndex = ArrayBlockingQueue.this.takeIndex;
            final int prevCycles = this.prevCycles;
            final int prevTakeIndex = this.prevTakeIndex;

            if (cycles != prevCycles || takeIndex != prevTakeIndex) {
                final int len = items.length;
                // how far takeIndex has advanced since the previous
                // operation of this iterator
                long dequeues = (cycles - prevCycles) * len
                    + (takeIndex - prevTakeIndex);

                // Check indices for invalidation
                if (invalidated(lastRet, prevTakeIndex, dequeues, len))
                    lastRet = REMOVED;
                if (invalidated(nextIndex, prevTakeIndex, dequeues, len))
                    nextIndex = REMOVED;
                if (invalidated(cursor, prevTakeIndex, dequeues, len))
                    cursor = takeIndex;

                if (cursor < 0 && nextIndex < 0 && lastRet < 0)
                    detach();
                else {
                    this.prevCycles = cycles;
                    this.prevTakeIndex = takeIndex;
                }
            }
        }

       //删除或更新的时候调用进行更新迭代器使用
        private void detach() {
            // Switch to detached mode
            // assert lock.getHoldCount() == 1;
            // assert cursor == NONE;
            // assert nextIndex < 0;
            // assert lastRet < 0 || nextItem == null;
            // assert lastRet < 0 ^ lastItem != null;
            if (prevTakeIndex >= 0) {
                // assert itrs != null;
                prevTakeIndex = DETACHED;
                // try to unlink from itrs (but not too hard)
                itrs.doSomeSweeping(true);
            }
        }

       //判断是否有下一个元素
        public boolean hasNext() {
            // assert lock.getHoldCount() == 0;
            if (nextItem != null)
                return true;
            noNext();
            return false;
        }
        //如果不没有下一个元素的通知操作
        private void noNext() {
            final ReentrantLock lock = ArrayBlockingQueue.this.lock;
            lock.lock();
            try {
                // assert cursor == NONE;
                // assert nextIndex == NONE;
                if (!isDetached()) {
                    // assert lastRet >= 0;
                    incorporateDequeues(); // might update lastRet
                    if (lastRet >= 0) {
                        lastItem = itemAt(lastRet);
                        // assert lastItem != null;
                        detach();
                    }
                }
                // assert isDetached();
                // assert lastRet < 0 ^ lastItem != null;
            } finally {
                lock.unlock();
            }
        }
        //获取下一个元素(带锁)
        public E next() {
            // assert lock.getHoldCount() == 0;
            final E x = nextItem;
            if (x == null)
                throw new NoSuchElementException();
            final ReentrantLock lock = ArrayBlockingQueue.this.lock;
            lock.lock();
            try {
                if (!isDetached())
                    incorporateDequeues();
                // assert nextIndex != NONE;
                // assert lastItem == null;
                lastRet = nextIndex;
                final int cursor = this.cursor;
                if (cursor >= 0) {
                    nextItem = itemAt(nextIndex = cursor);
                    // assert nextItem != null;
                    this.cursor = incCursor(cursor);
                } else {
                    nextIndex = NONE;
                    nextItem = null;
                }
            } finally {
                lock.unlock();
            }
            return x;
        }
        //删除(带锁)
        public void remove() {
            // assert lock.getHoldCount() == 0;
            final ReentrantLock lock = ArrayBlockingQueue.this.lock;
            lock.lock();
            try {
                if (!isDetached())
                    incorporateDequeues(); // might update lastRet or detach
                final int lastRet = this.lastRet;
                this.lastRet = NONE;
                if (lastRet >= 0) {
                    if (!isDetached())
                        removeAt(lastRet);
                    else {
                        final E lastItem = this.lastItem;
                        // assert lastItem != null;
                        this.lastItem = null;
                        if (itemAt(lastRet) == lastItem)
                            removeAt(lastRet);
                    }
                } else if (lastRet == NONE)
                    throw new IllegalStateException();
                // else lastRet == REMOVED and the last returned element was
                // previously asynchronously removed via an operation other
                // than this.remove(), so nothing to do.

                if (cursor < 0 && nextIndex < 0)
                    detach();
            } finally {
                lock.unlock();
                // assert lastRet == NONE;
                // assert lastItem == null;
            }
        }

        //迭代器为空时调用,清空所有,进行重置
        void shutdown() {
            // assert lock.getHoldCount() == 1;
            cursor = NONE;
            if (nextIndex >= 0)
                nextIndex = REMOVED;
            if (lastRet >= 0) {
                lastRet = REMOVED;
                lastItem = null;
            }
            prevTakeIndex = DETACHED;
            // Don't set nextItem to null because we must continue to be
            // able to return it on next().
            //
            // Caller will unlink from itrs when convenient.
        }
        //获取下标
        private int distance(int index, int prevTakeIndex, int length) {
            int distance = index - prevTakeIndex;
            if (distance < 0)
                distance += length;
            return distance;
        }

       //删除指定元素的索引与下标
        boolean removedAt(int removedIndex) {
            // assert lock.getHoldCount() == 1;
            if (isDetached())
                return true;

            final int cycles = itrs.cycles;
            final int takeIndex = ArrayBlockingQueue.this.takeIndex;
            final int prevCycles = this.prevCycles;
            final int prevTakeIndex = this.prevTakeIndex;
            final int len = items.length;
            int cycleDiff = cycles - prevCycles;
            if (removedIndex < takeIndex)
                cycleDiff++;
            final int removedDistance =
                (cycleDiff * len) + (removedIndex - prevTakeIndex);
            // assert removedDistance >= 0;
            int cursor = this.cursor;
            if (cursor >= 0) {
                int x = distance(cursor, prevTakeIndex, len);
                if (x == removedDistance) {
                    if (cursor == putIndex)
                        this.cursor = cursor = NONE;
                }
                else if (x > removedDistance) {
                    // assert cursor != prevTakeIndex;
                    this.cursor = cursor = dec(cursor);
                }
            }
            int lastRet = this.lastRet;
            if (lastRet >= 0) {
                int x = distance(lastRet, prevTakeIndex, len);
                if (x == removedDistance)
                    this.lastRet = lastRet = REMOVED;
                else if (x > removedDistance)
                    this.lastRet = lastRet = dec(lastRet);
            }
            int nextIndex = this.nextIndex;
            if (nextIndex >= 0) {
                int x = distance(nextIndex, prevTakeIndex, len);
                if (x == removedDistance)
                    this.nextIndex = nextIndex = REMOVED;
                else if (x > removedDistance)
                    this.nextIndex = nextIndex = dec(nextIndex);
            }
            else if (cursor < 0 && nextIndex < 0 && lastRet < 0) {
                this.prevTakeIndex = DETACHED;
                return true;
            }
            return false;
        }

       //判断迭代器是否已移动,如果是返回true 否返回false
        boolean takeIndexWrapped() {
            // assert lock.getHoldCount() == 1;
            //已移除
            if (isDetached())
                return true;
            //还存在进行移除处理
            if (itrs.cycles - prevCycles > 1) {
                // All the elements that existed at the time of the last
                // operation are gone, so abandon further iteration.
                shutdown();
                return true;
            }
            //都不是则返回false
            return false;
        }

    //返回该队列元素的Spliterator列表
    public Spliterator<E> spliterator() {
        return Spliterators.spliterator
            (this, Spliterator.ORDERED | Spliterator.NONNULL |
             Spliterator.CONCURRENT);
    }

    //反序列化对象
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {

        // Read in items array and various fields
        s.defaultReadObject();

        // Check invariants over count and index fields. Note that
        // if putIndex==takeIndex, count can be either 0 or items.length.
        if (items.length == 0 ||
            takeIndex < 0 || takeIndex >= items.length ||
            putIndex < 0 || putIndex >= items.length ||
            count < 0     || count > items.length ||
            Math.floorMod(putIndex - takeIndex, items.length) !=
            Math.floorMod(count, items.length)) {
            throw new java.io.InvalidObjectException("invariants violated");
        }
    }

}

java.util.concurrent.LinkedBlockingQueue 的源码实现

3e6539dcb97a0f20352151fd798b969e.png

同样了解一下基础,LinkedBlockingQueue 也是一个阻塞队列,继承AbstractQueue实现BlockingQueue 基于链表来实现的,默认是元界的,当然也可以通过构造方法实现有界;

package java.util.concurrent;

import java.util.concurrent.atomic.AtomicInteger;
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.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;

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



    //链表节点类
    static class Node<E> {
        //元素
        E item;

        //一下个节点
        Node<E> next;
        //构造方法
        Node(E x) { item = x; }
    }

    //初始容量
    private final int capacity;

    //当前元数数量(俱备原子与内存可见)
    private final AtomicInteger count = new AtomicInteger();

    //头节点
    transient Node<E> head;

    //尾节点
    private transient Node<E> last;
    //重入锁
    private final ReentrantLock takeLock = new ReentrantLock();

    //不是空 条件
    private final Condition notEmpty = takeLock.newCondition();

    //添加锁
    private final ReentrantLock putLock = new ReentrantLock();

    //未满条件
    private final Condition notFull = putLock.newCondition();

    //单例不为空
    private void signalNotEmpty() {
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            //唤醒一个等待线程
            notEmpty.signal();
        } finally {
            //解锁
            takeLock.unlock();
        }
    }

    //元素出队后的调用,唤醒一个线程
    private void signalNotFull() {
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            notFull.signal();
        } finally {
            putLock.unlock();
        }
    }

   //插到队列尾部
    private void enqueue(Node<E> node) {
        // assert putLock.isHeldByCurrentThread();
        // assert last.next == null;
        last = last.next = node;
    }

    //从队列头中移除一个节点。
    private E dequeue() {
        // assert takeLock.isHeldByCurrentThread();
        // assert head.item == null;
        //获取队头
        Node<E> h = head;
        //获取下一个节点
        Node<E> first = h.next;
        //重新指向
        h.next = h; // help GC
        //重新指向
        head = first;
        //赋空
        E x = first.item;
        first.item = null;
        //返回节点
        return x;
    }

    //上锁 防止 添加元素 和移除元素
    void fullyLock() {
        putLock.lock();
        takeLock.lock();
    }

    //解锁
    void fullyUnlock() {
        takeLock.unlock();
        putLock.unlock();
    }



     //构造方法 初始化容量为Integer最大值
    public LinkedBlockingQueue() {
        this(Integer.MAX_VALUE);
    }

    //指定初始化容量
    public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node<E>(null);
    }

   //构造方法(带入参)
    public LinkedBlockingQueue(Collection<? extends E> c) {
        this(Integer.MAX_VALUE);
        //获取锁 上锁
        final ReentrantLock putLock = this.putLock;
        putLock.lock(); // Never contended, but necessary for visibility
        try {
            int n = 0;
            //循环入队 如果为空则抛出异常, 如果超过容量抛出异常
            for (E e : c) {
                if (e == null)
                    throw new NullPointerException();
                if (n == capacity)
                    throw new IllegalStateException("Queue full");
                enqueue(new Node<E>(e));
                ++n;
            }
            count.set(n);
        } finally {
            //解锁
            putLock.unlock();
        }
    }

   //获取数量
    public int size() {
        return count.get();
    }

    //获取剩余队列容量
    public int remainingCapacity() {
        return capacity - count.get();
    }

    //添加到队列尾部
    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)
            //为空不为空通知
            signalNotEmpty();
    }

    //带过期时间的入队
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {
        //为空抛出异常
        if (e == null) throw new NullPointerException();
        //纳敏
        long nanos = unit.toNanos(timeout);
        int c = -1;
        //获取锁 中断上锁
        final ReentrantLock putLock = this.putLock;
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly();
        try {
            //同上类似
            while (count.get() == capacity) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(new Node<E>(e));
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return true;
    }

    //将元素插入元素尾部(逻辑同上)
    public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
        if (count.get() == capacity)
            return false;
        int c = -1;
        Node<E> node = new Node<E>(e);
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            if (count.get() < capacity) {
                enqueue(node);
                c = count.getAndIncrement();
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return c >= 0;
    }
    //获取队列第一个元素(队尾取)
    public E take() throws InterruptedException {
        E x;
        int c = -1;
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) {
                notEmpty.await();
            }
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }
    //带过期时间的获取队列首位(逻辑同上)
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        E x = null;
        int c = -1;
        long nanos = unit.toNanos(timeout);
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }
    //取队列首位(逻辑同上)
    public E poll() {
        final AtomicInteger count = this.count;
        if (count.get() == 0)
            return null;
        E x = null;
        int c = -1;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            if (count.get() > 0) {
                x = dequeue();
                c = count.getAndDecrement();
                if (c > 1)
                    notEmpty.signal();
            }
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }
    //获取下一个元素
    public E peek() {
        if (count.get() == 0)
            return null;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            Node<E> first = head.next;
            if (first == null)
                return null;
            else
                return first.item;
        } finally {
            takeLock.unlock();
        }
    }

    //将内部的p与前端的节点断开链接
    void unlink(Node<E> p, Node<E> trail) {
        // assert isFullyLocked();
        // p.next is not changed, to allow iterators that are
        // traversing p to maintain their weak-consistency guarantee.
        p.item = null;
        trail.next = p.next;
        if (last == p)
            last = trail;
        if (count.getAndDecrement() == capacity)
            notFull.signal();
    }

    //从队列中移队珍上节点
    public boolean remove(Object o) {
        if (o == null) return false;
        fullyLock();
        try {
            for (Node<E> trail = head, p = trail.next;
                 p != null;
                 trail = p, p = p.next) {
                if (o.equals(p.item)) {
                    unlink(p, trail);
                    return true;
                }
            }
            return false;
        } finally {
            fullyUnlock();
        }
    }

    //判断是否包含该元素
    public boolean contains(Object o) {
        if (o == null) return false;
        fullyLock();
        try {
            //循环判断
            for (Node<E> p = head.next; p != null; p = p.next)
                if (o.equals(p.item))
                    return true;
            return false;
        } finally {
            fullyUnlock();
        }
    }

    //将队列转成数组
    public Object[] toArray() {
        fullyLock();
        try {
            int size = count.get();
            Object[] a = new Object[size];
            int k = 0;
            for (Node<E> p = head.next; p != null; p = p.next)
                a[k++] = p.item;
            return a;
        } finally {
            fullyUnlock();
        }
    }

    //转成数组
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        fullyLock();
        try {
            int size = count.get();
            if (a.length < size)
                a = (T[])java.lang.reflect.Array.newInstance
                    (a.getClass().getComponentType(), size);

            int k = 0;
            for (Node<E> p = head.next; p != null; p = p.next)
                a[k++] = (T)p.item;
            if (a.length > k)
                a[k] = null;
            return a;
        } finally {
            fullyUnlock();
        }
    }
    //转成字符串
    public String toString() {
        fullyLock();
        try {
            Node<E> p = head.next;
            if (p == null)
                return "[]";

            StringBuilder sb = new StringBuilder();
            sb.append('[');
            for (;;) {
                E e = p.item;
                sb.append(e == this ? "(this Collection)" : e);
                p = p.next;
                if (p == null)
                    return sb.append(']').toString();
                sb.append(',').append(' ');
            }
        } finally {
            fullyUnlock();
        }
    }

    //清空队列
    public void clear() {
        fullyLock();
        try {
            for (Node<E> p, h = head; (p = h.next) != null; h = p) {
                h.next = h;
                p.item = null;
            }
            head = last;
            // assert head.item == null && head.next == null;
            if (count.getAndSet(0) == capacity)
                notFull.signal();
        } finally {
            fullyUnlock();
        }
    }

    //转成一个新列表
        public int drainTo(Collection<? super E> c) {
        return drainTo(c, Integer.MAX_VALUE);
    }

   //新例 表的实现,
    public int drainTo(Collection<? super E> c, int maxElements) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        if (maxElements <= 0)
            return 0;
        boolean signalNotFull = false;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            int n = Math.min(maxElements, count.get());
            // count.get provides visibility to first n Nodes
            Node<E> h = head;
            int i = 0;
            try {
                //循环添加
                while (i < n) {
                    Node<E> p = h.next;
                    c.add(p.item);
                    p.item = null;
                    h.next = h;
                    h = p;
                    ++i;
                }
                return n;
            } finally {
                // Restore invariants even if c.add() threw
                if (i > 0) {
                    // assert h.item == null;
                    head = h;
                    signalNotFull = (count.getAndAdd(-i) == capacity);
                }
            }
        } finally {
            takeLock.unlock();
            if (signalNotFull)
                signalNotFull();
        }
    }

    //创建一个新迭代器
    public Iterator<E> iterator() {
        return new Itr();
    }
    //迭代器
    private class Itr implements Iterator<E> {
       
        //当前元素
        private Node<E> current;
        //最后获取
        private Node<E> lastRet;
        //当前元素
        private E currentElement;

        Itr() {
            fullyLock();
            try {
                current = head.next;
                if (current != null)
                    currentElement = current.item;
            } finally {
                fullyUnlock();
            }
        }
        //判断是否有下一节点
        public boolean hasNext() {
            return current != null;
        }

        //下一个节点
        private Node<E> nextNode(Node<E> p) {
            for (;;) {
                Node<E> s = p.next;
                if (s == p)
                    return head.next;
                if (s == null || s.item != null)
                    return s;
                p = s;
            }
        }
        //获取下一个节点
        public E next() {
            fullyLock();
            try {
                if (current == null)
                    throw new NoSuchElementException();
                E x = currentElement;
                lastRet = current;
                current = nextNode(current);
                currentElement = (current == null) ? null : current.item;
                return x;
            } finally {
                fullyUnlock();
            }
        }
        //移取一个元素(全部移除)
        public void remove() {
            if (lastRet == null)
                throw new IllegalStateException();
            fullyLock();
            try {
                Node<E> node = lastRet;
                lastRet = null;
                for (Node<E> trail = head, p = trail.next;
                     p != null;
                     trail = p, p = p.next) {
                    if (p == node) {
                        break;
                        unlink(p, trail);
                    }
                }
            } finally {
                fullyUnlock();
            }
        }
    }

    //自定义迭代器
    static final class LBQSpliterator<E> implements Spliterator<E> {
        static final int MAX_BATCH = 1 << 25; // max batch array size;
        final LinkedBlockingQueue<E> queue;
        Node<E> current; // current node; null until initialized
        int batch; // batch size for splits
        boolean exhausted; // true when no more nodes
        long est; // size estimate
        LBQSpliterator(LinkedBlockingQueue<E> queue) {
            this.queue = queue;
            this.est = queue.size();
        }

        public long estimateSize() { return est; }
        //尝试分割
        public Spliterator<E> trySplit() {
            Node<E> h;
            final LinkedBlockingQueue<E> q = this.queue;
            int b = batch;
            int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
            if (!exhausted &&
                ((h = current) != null || (h = q.head.next) != null) &&
                h.next != null) {
                Object[] a = new Object[n];
                int i = 0;
                Node<E> p = current;
                q.fullyLock();
                try {
                    if (p != null || (p = q.head.next) != null) {
                        do {
                            if ((a[i] = p.item) != null)
                                ++i;
                        } while ((p = p.next) != null && i < n);
                    }
                } finally {
                    q.fullyUnlock();
                }
                if ((current = p) == null) {
                    est = 0L;
                    exhausted = true;
                }
                else if ((est -= i) < 0L)
                    est = 0L;
                if (i > 0) {
                    batch = i;
                    return Spliterators.spliterator
                        (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
                         Spliterator.CONCURRENT);
                }
            }
            return null;
        }
        //循环给每个元素赋值入队
        public void forEachRemaining(Consumer<? super E> action) {
            if (action == null) throw new NullPointerException();
            final LinkedBlockingQueue<E> q = this.queue;
            if (!exhausted) {
                exhausted = true;
                Node<E> p = current;
                do {
                    E e = null;
                    q.fullyLock();
                    try {
                        if (p == null)
                            p = q.head.next;
                        while (p != null) {
                            e = p.item;
                            p = p.next;
                            if (e != null)
                                break;
                        }
                    } finally {
                        q.fullyUnlock();
                    }
                    if (e != null)
                        action.accept(e);
                } while (p != null);
            }
        }
        //判断是否存在元素
        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null) throw new NullPointerException();
            final LinkedBlockingQueue<E> q = this.queue;
            if (!exhausted) {
                E e = null;
                q.fullyLock();
                try {
                    if (current == null)
                        current = q.head.next;
                    while (current != null) {
                        e = current.item;
                        current = current.next;
                        if (e != null)
                            break;
                    }
                } finally {
                    q.fullyUnlock();
                }
                if (current == null)
                    exhausted = true;
                if (e != null) {
                    action.accept(e);
                    return true;
                }
            }
            return false;
        }
        //返回该Spliterator及其元素的一组特征。
        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.NONNULL |
                Spliterator.CONCURRENT;
        }
    }

    //获取元素到迭代器
    public Spliterator<E> spliterator() {
        return new LBQSpliterator<E>(this);
    }

    //将此队列保存到流(即序列化它)。
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {

        fullyLock();
        try {
            // Write out any hidden stuff, plus capacity
            s.defaultWriteObject();

            // Write out all elements in the proper order.
            for (Node<E> p = head.next; p != null; p = p.next)
                s.writeObject(p.item);

            // Use trailing null as sentinel
            s.writeObject(null);
        } finally {
            fullyUnlock();
        }
    }

    //读取对象
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in capacity, and any hidden stuff
        s.defaultReadObject();

        count.set(0);
        last = head = new Node<E>(null);

        // 读入所有元素并放入队列
        for (;;) {
            @SuppressWarnings("unchecked")
            E item = (E)s.readObject();
            if (item == null)
                break;
            add(item);
        }
    }

}

java.util.concurrent.PriorityBlockingQueue 的源码实现
94ded353f6eb2da708b6bc75faeb6e47.png

PriorityBlockingQueue 也是一个基于优先级别阻塞队列,继承AbstractQueue实现BlockingQueue 基于数组来实现无界队列;其内部优先级主要通过比较器来实现这个逻辑,如果条件高的优先被线程处理,当然这个取决于你的配置,默认也可以不配置。例如:医院有 紧急、中等、一般 挂号,医生要处理的,如果像那种一进来就需要紧急抢救的当然就不能跟大家一样等待。

package java.util.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.AbstractQueue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.function.Consumer;
import sun.misc.SharedSecrets;
//基于优先级的阻塞队列
@SuppressWarnings("unchecked")
public class PriorityBlockingQueue<E> extends AbstractQueue<E>
    implements BlockingQueue<E>, java.io.Serializable {
    private static final long serialVersionUID = 5595510919245408276L;



    /**
     * 默认队列容量为11
     */
    private static final int DEFAULT_INITIAL_CAPACITY = 11;

    //限制队列最大数 为 整形的最大值-8
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    //优先级队列
    private transient Object[] queue;

    //队列当前数量
    private transient int size;

    //优先级排序 如果默认使用自然排序则为空
    private transient Comparator<? super E> comparator;

    /**
     *重入锁
     */
    private final ReentrantLock lock;

    /**
     * 不为空条件
     */
    private final Condition notEmpty;

    /**
     * 自旋锁人 transient是不保存在磁盘中
     */
    private transient volatile int allocationSpinLock;

   //优先级队列(序列化)
    private PriorityQueue<E> q;

   //构造方法
    public PriorityBlockingQueue() {
        this(DEFAULT_INITIAL_CAPACITY, null);
    }

   //带指定容量构造方法
    public PriorityBlockingQueue(int initialCapacity) {
        this(initialCapacity, null);
    }

   //带指定容量及比较器
    public PriorityBlockingQueue(int initialCapacity,
                                 Comparator<? super E> comparator) {
        if (initialCapacity < 1)
            throw new IllegalArgumentException();
        this.lock = new ReentrantLock();
        this.notEmpty = lock.newCondition();
        this.comparator = comparator;
        this.queue = new Object[initialCapacity];
    }

    //构建方法 带排序器
    public PriorityBlockingQueue(Collection<? extends E> c) {
        //获取重入锁及条件
        this.lock = new ReentrantLock();
        this.notEmpty = lock.newCondition();
        boolean heapify = true; // true if not known to be in heap order
        boolean screen = true; // true if must screen for nulls
        //如果是有序庥,则不需要堆有序化
        if (c instanceof SortedSet<?>) {
            SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
            this.comparator = (Comparator<? super E>) ss.comparator();
            heapify = false;
        }
        //如果为PriorityBlockingQueue 类型 不进行堆有序化
        else if (c instanceof PriorityBlockingQueue<?>) {
            PriorityBlockingQueue<? extends E> pq =
                (PriorityBlockingQueue<? extends E>) c;
            this.comparator = (Comparator<? super E>) pq.comparator();
            screen = false;
            if (pq.getClass() == PriorityBlockingQueue.class) // exact match
                heapify = false;
        }
        //获取数组
        Object[] a = c.toArray();
        int n = a.length;
        // If c.toArray incorrectly doesn't return Object[], copy it.
        //不是Object[]类型进行复制
        if (a.getClass() != Object[].class)
            a = Arrays.copyOf(a, n, Object[].class);
        //screen不为false 且 对比器不为空进行循环便利 ,如果有内容为Null 跑出空指针异常
        if (screen && (n == 1 || this.comparator != null)) {
            for (int i = 0; i < n; ++i)
                if (a[i] == null)
                    throw new NullPointerException();
        }
        this.queue = a;
        this.size = n;
        if (heapify)
            //堆有序化
            heapify();
    }

    //尝试扩容
    private void tryGrow(Object[] array, int oldCap) {
        //先解锁
        lock.unlock(); // must release and then re-acquire main lock
        //新数组
        Object[] newArray = null;
        //判断锁状态 和重新获取锁
        if (allocationSpinLock == 0 &&
            UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset,
                                     0, 1)) {
            //重新转换
            try {
                int newCap = oldCap + ((oldCap < 64) ?
                                       (oldCap + 2) : // grow faster if small
                                       (oldCap >> 1));
                if (newCap - MAX_ARRAY_SIZE > 0) { // possible overflow
                    int minCap = oldCap + 1;
                    if (minCap < 0 || minCap > MAX_ARRAY_SIZE)
                        throw new OutOfMemoryError();
                    newCap = MAX_ARRAY_SIZE;
                }
                //最后进行初始化大小
                if (newCap > oldCap && queue == array)
                    newArray = new Object[newCap];
            } finally {
                allocationSpinLock = 0;
            }
        }
        //如果另外一线程正在分配,则退出
        if (newArray == null) // back off if another thread is allocating
            Thread.yield();
        //上锁
        lock.lock();
        //复制
        if (newArray != null && queue == array) {
            queue = newArray;
            System.arraycopy(array, 0, newArray, 0, oldCap);
        }
    }

    //获取一个元素
    private E dequeue() {
        int n = size - 1;
        //小于0直接返回空
        if (n < 0)
            return null;
        else {
            //获取队列数据
            Object[] array = queue;
            //获取第一个
            E result = (E) array[0];
            //最后一个置为空
            E x = (E) array[n];
            array[n] = null;
            Comparator<? super E> cmp = comparator;
            //将x插到第一位
            if (cmp == null)
                siftDownComparable(0, x, array, n);
            else
                //带比较器判断x插到第0位
                siftDownUsingComparator(0, x, array, n, cmp);
            size = n;
            //返回结果
            return result;
        }
    }

    //将x插到第k位
    private static <T> void siftUpComparable(int k, T x, Object[] array) {
        Comparable<? super T> key = (Comparable<? super T>) x;
        //当k大于0 进行迭代
        while (k > 0) {
            //获取对象
            int parent = (k - 1) >>> 1;
            Object e = array[parent];
            //对比是否大于0如果是跳出
            if (key.compareTo((T) e) >= 0)
                break;
            array[k] = e;
            k = parent;
        }
        array[k] = key;
    }
    //上浮操作(带比较器)
    private static <T> void siftUpUsingComparator(int k, T x, Object[] array,
                                       Comparator<? super T> cmp) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = array[parent];
            if (cmp.compare(x, (T) e) >= 0)
                break;
            array[k] = e;
            k = parent;
        }
        array[k] = x;
    }

    //下沉操作,带比较器
    private static <T> void siftDownComparable(int k, T x, Object[] array,
                                               int n) {
        //n必须不能第0位
        if (n > 0) {
            //获取传进来的比较器
            Comparable<? super T> key = (Comparable<? super T>)x;
            //右移一位获取下标
            int half = n >>> 1; // loop while a non-leaf
            //循环 进行交换位置
            while (k < half) {
                int child = (k << 1) + 1; // assume left child is least
                Object c = array[child];
                int right = child + 1;
                if (right < n &&
                    ((Comparable<? super T>) c).compareTo((T) array[right]) > 0)
                    c = array[child = right];
                //如果比较结果小于0则跳出
                if (key.compareTo((T) c) <= 0)
                    break;
                //重新赋值
                array[k] = c;
                //交换位置
                k = child;
            }
            array[k] = key;
        }
    }
    //同上类似
    private static <T> void siftDownUsingComparator(int k, T x, Object[] array,
                                                    int n,
                                                    Comparator<? super T> cmp) {
        if (n > 0) {
            int half = n >>> 1;
            while (k < half) {
                int child = (k << 1) + 1;
                Object c = array[child];
                int right = child + 1;
                if (right < n && cmp.compare((T) c, (T) array[right]) > 0)
                    c = array[child = right];
                if (cmp.compare(x, (T) c) <= 0)
                    break;
                array[k] = c;
                k = child;
            }
            array[k] = x;
        }
    }

    //堆有序化
    private void heapify() {
        Object[] array = queue;
        int n = size;
        int half = (n >>> 1) - 1;
        Comparator<? super E> cmp = comparator;
        if (cmp == null) {
            for (int i = half; i >= 0; i--)
                //下沉(没比较器)
                siftDownComparable(i, (E) array[i], array, n);
        }
        else {
            for (int i = half; i >= 0; i--)
                //下沉(带比较器)
                siftDownUsingComparator(i, (E) array[i], array, n, cmp);
        }
    }

    //新增元素到尾部
    public boolean add(E e) {
        return offer(e);
    }

    //新增元素实现
    public boolean offer(E e) {
        //为空跑出异常
        if (e == null)
            throw new NullPointerException();
        //获取重入锁 上锁
        final ReentrantLock lock = this.lock;
        lock.lock();
        int n, cap;
        Object[] array;
        //循环判断是不是满了,是否需要扩容
        while ((n = size) >= (cap = (array = queue).length))
            tryGrow(array, cap);
        try {
            //获取比较器
            Comparator<? super E> cmp = comparator;
            if (cmp == null)
                //没有比较顺走上浮操作
                siftUpComparable(n, e, array);
            else
                //带比较器走上浮操作
                siftUpUsingComparator(n, e, array, cmp);
            size = n + 1;
            //通知其他空闲线程
            notEmpty.signal();
        } finally {
            //解锁
            lock.unlock();
        }
        return true;
    }

    //添加方法(带线程等待)
    public void put(E e) {
        offer(e); // never need to block
    }

    //添加操作
    public boolean offer(E e, long timeout, TimeUnit unit) {
        return offer(e); // never need to block
    }
    //从队列中获取一个元素(带锁)
    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
    //从队头中获取一个元素()
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        E result;
        try {
            while ( (result = dequeue()) == null)
                //队列为空进行等待
                notEmpty.await();
        } finally {
            lock.unlock();
        }
        return result;
    }
    //带超时时间从队列中获取一个元素(逻辑都差不多)
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        E result;
        try {
            while ( (result = dequeue()) == null && nanos > 0)
                nanos = notEmpty.awaitNanos(nanos);
        } finally {
            lock.unlock();
        }
        return result;
    }
    //从队列中获取一个元素(不等待)
    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (size == 0) ? null : (E) queue[0];
        } finally {
            lock.unlock();
        }
    }

    //返回比较器
    public Comparator<? super E> comparator() {
        return comparator;
    }
    //获取队列大小
    public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return size;
        } finally {
            lock.unlock();
        }
    }

    //初始化最大值
    public int remainingCapacity() {
        return Integer.MAX_VALUE;
    }
    //判断元素是否在队列中,如果是返回下标如果不是返回-1
    private int indexOf(Object o) {
        if (o != null) {
            Object[] array = queue;
            int n = size;
            for (int i = 0; i < n; i++)
                if (o.equals(array[i]))
                    return i;
        }
        return -1;
    }

    //从队列中移除一个元素(这里有上下浮操作)
    private void removeAt(int i) {
        Object[] array = queue;
        int n = size - 1;
        if (n == i) // removed last element
            array[i] = null;
        else {
            E moved = (E) array[n];
            array[n] = null;
            Comparator<? super E> cmp = comparator;
            if (cmp == null)
                siftDownComparable(i, moved, array, n);
            else
                siftDownUsingComparator(i, moved, array, n, cmp);
            if (array[i] == moved) {
                if (cmp == null)
                    siftUpComparable(i, moved, array);
                else
                    siftUpUsingComparator(i, moved, array, cmp);
            }
        }
        size = n;
    }

    //有返回结果 从队列中移除一个元素 如果成功返回true 失败返回false(带锁)
    public boolean remove(Object o) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int i = indexOf(o);
            if (i == -1)
                return false;
            removeAt(i);
            return true;
        } finally {
            lock.unlock();
        }
    }

    //带版本的移除队列中的元素(逻辑是先找到下标再移掉)
    void removeEQ(Object o) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] array = queue;
            for (int i = 0, n = size; i < n; i++) {
                if (o == array[i]) {
                    removeAt(i);
                    break;
                }
            }
        } finally {
            lock.unlock();
        }
    }

    //判断队列是否包含该元素(带锁)
    public boolean contains(Object o) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return indexOf(o) != -1;
        } finally {
            lock.unlock();
        }
    }

   //将队列转成数组返回
    public Object[] toArray() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return Arrays.copyOf(queue, size);
        } finally {
            lock.unlock();
        }
    }
    //转成字符串方法
    public String toString() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int n = size;
            if (n == 0)
                return "[]";
            StringBuilder sb = new StringBuilder();
            sb.append('[');
            for (int i = 0; i < n; ++i) {
                Object e = queue[i];
                sb.append(e == this ? "(this Collection)" : e);
                if (i != n - 1)
                    sb.append(',').append(' ');
            }
            return sb.append(']').toString();
        } finally {
            lock.unlock();
        }
    }

   //转成一个新列表
    public int drainTo(Collection<? super E> c) {
        return drainTo(c, Integer.MAX_VALUE);
    }

    //新实例表的实现
    public int drainTo(Collection<? super E> c, int maxElements) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        if (maxElements <= 0)
            return 0;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int n = Math.min(size, maxElements);
            for (int i = 0; i < n; i++) {
                c.add((E) queue[0]); // In this order, in case add() throws.
                dequeue();
            }
            return n;
        } finally {
            lock.unlock();
        }
    }

    //清空队列
    public void clear() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] array = queue;
            int n = size;
            size = 0;
            for (int i = 0; i < n; i++)
                array[i] = null;
        } finally {
            lock.unlock();
        }
    }

    //转成数组的实现
    public <T> T[] toArray(T[] a) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int n = size;
            if (a.length < n)
                // Make a new array of a's runtime type, but my contents:
                return (T[]) Arrays.copyOf(queue, size, a.getClass());
            System.arraycopy(queue, 0, a, 0, n);
            if (a.length > n)
                a[n] = null;
            return a;
        } finally {
            lock.unlock();
        }
    }

    //创建一个新的迭代器
    public Iterator<E> iterator() {
        return new Itr(toArray());
    }
    //迭代器实现 比其他简单多了
    final class Itr implements Iterator<E> {
        //全部的内容
        final Object[] array; // Array of all elements
        //游标(下标)
        int cursor; // index of next element to return
        //最后一个元素的索绯红
        int lastRet; // index of last element, or -1 if no such
        //构造方法
        Itr(Object[] array) {
            lastRet = -1;
            this.array = array;
        }
        //判断是否有下一个元素
        public boolean hasNext() {
            return cursor < array.length;
        }
        //下一个元素
        public E next() {
            //超过数组直接抛出异常
            if (cursor >= array.length)
                throw new NoSuchElementException();
            lastRet = cursor;
            return (E)array[cursor++];
        }
        //移除元素
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            removeEQ(array[lastRet]);
            lastRet = -1;
        }
    }

   //将流转化为列表中
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        lock.lock();
        try {
            // avoid zero capacity argument
            q = new PriorityQueue<E>(Math.max(size, 1), comparator);
            q.addAll(this);
            s.defaultWriteObject();
        } finally {
            q = null;
            lock.unlock();
        }
    }

    //读取流到列表中
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        try {
            s.defaultReadObject();
            int sz = q.size();
            SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, sz);
            this.queue = new Object[sz];
            comparator = q.comparator();
            addAll(q);
        } finally {
            q = null;
        }
    }

    //自定义迭代器(逻辑类似)
    static final class PBQSpliterator<E> implements Spliterator<E> {
        final PriorityBlockingQueue<E> queue;
        Object[] array;
        int index;
        int fence;

        PBQSpliterator(PriorityBlockingQueue<E> queue, Object[] array,
                       int index, int fence) {
            this.queue = queue;
            this.array = array;
            this.index = index;
            this.fence = fence;
        }

        final int getFence() {
            int hi;
            if ((hi = fence) < 0)
                hi = fence = (array = queue.toArray()).length;
            return hi;
        }

        public Spliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null :
                new PBQSpliterator<E>(queue, array, lo, index = mid);
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> action) {
            Object[] a; int i, hi; // hoist accesses and checks from loop
            if (action == null)
                throw new NullPointerException();
            if ((a = array) == null)
                fence = (a = queue.toArray()).length;
            if ((hi = fence) <= a.length &&
                (i = index) >= 0 && i < (index = hi)) {
                do { action.accept((E)a[i]); } while (++i < hi);
            }
        }

        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null)
                throw new NullPointerException();
            if (getFence() > index && index >= 0) {
                @SuppressWarnings("unchecked") E e = (E) array[index++];
                action.accept(e);
                return true;
            }
            return false;
        }

        public long estimateSize() { return (long)(getFence() - index); }

        public int characteristics() {
            return Spliterator.NONNULL | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

    /**
     * Returns a {@link Spliterator} over the elements in this queue.
     *
     * <p>The returned spliterator is
     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
     *
     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
     * {@link Spliterator#NONNULL}.
     *
     * @implNote
     * The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED}.
     *
     * @return a {@code Spliterator} over the elements in this queue
     * @since 1.8
     */
    public Spliterator<E> spliterator() {
        return new PBQSpliterator<E>(this, null, 0, -1);
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe UNSAFE;
    private static final long allocationSpinLockOffset;
    static {
        try {
            //默认采用Unsafe来实现
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> k = PriorityBlockingQueue.class;
            allocationSpinLockOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("allocationSpinLock"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }
}

java.util.concurrent.BlockingDeque 与 java.util.concurrent.LinkedBlockingDeque 源码实现

7cf4377f7400af34a364d38aadc9649e.png

这个有一个区别就是LinkedBlockingDeque 一个双向链表实现双向的并发阻塞队列,有两种操作方式 FIFO和FILO。

c0bf4b6b127e29e3ac3c8ab6de647514.png

package java.util.concurrent;

import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
//双向链表阻塞队列
public class LinkedBlockingDeque<E>
    extends AbstractQueue<E>
    implements BlockingDeque<E>, java.io.Serializable {



    private static final long serialVersionUID = -387911632671998426L;
    //双向链表类
    static final class Node<E> {
        //节点
        E item;

       //上一个节点
        Node<E> prev;

        //下一个节点
        Node<E> next;
        //构造方法
        Node(E x) {
            item = x;
        }
    }

    //首节点
    transient Node<E> first;

    //尾节点
    transient Node<E> last;
    //队列中个数
    private transient int count;
    //队列容量
    private final int capacity;

    //重入锁
    final ReentrantLock lock = new ReentrantLock();

    //不为空条件
    private final Condition notEmpty = lock.newCondition();

    //不满条件
    private final Condition notFull = lock.newCondition();

    //构造方法 默认为Integer.MAX_VALUE 最大值
    public LinkedBlockingDeque() {
        this(Integer.MAX_VALUE);
    }

    //指定容量的初始化
    public LinkedBlockingDeque(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
    }

   //带列表的初始化
    public LinkedBlockingDeque(Collection<? extends E> c) {
        //初始化大小
        this(Integer.MAX_VALUE);
        //获取重入锁 并上锁
        final ReentrantLock lock = this.lock;
        lock.lock(); // Never contended, but necessary for visibility
        try {
            //循环 添加 如果 对象为空 或 入队失败直接抛出异常
            for (E e : c) {
                if (e == null)
                    throw new NullPointerException();
                if (!linkLast(new Node<E>(e)))
                    throw new IllegalStateException("Deque full");
            }
        } finally {
            lock.unlock();
        }
    }


    //添加直头部第一个节点
    private boolean linkFirst(Node<E> node) {
        // assert lock.isHeldByCurrentThread();
        if (count >= capacity)
            return false;
        //牛逼这样不用循环去挪动下标
        Node<E> f = first;
        node.next = f;
        first = node;
        if (last == null)
            last = node;
        else
            f.prev = node;
        ++count;
        //唤醒其他等待线程
        notEmpty.signal();
        return true;
    }

    //插到尾部 如果满则返回false
    private boolean linkLast(Node<E> node) {
        // assert lock.isHeldByCurrentThread();
        if (count >= capacity)
            return false;
        //一样的操作,不用循环去遍历,直接指向最后一个节点为上一个节点
        Node<E> l = last;
        node.prev = l;
        last = node;
        if (first == null)
            first = node;
        else
            l.next = node;
        ++count;
        notEmpty.signal();
        return true;
    }

    //移出队列第一个节点
    private E unlinkFirst() {
        // assert lock.isHeldByCurrentThread();
        //一样不需要重新循环 直接移出后指定头节点为下一个节点就OK了
        Node<E> f = first;
        if (f == null)
            return null;
        Node<E> n = f.next;
        E item = f.item;
        f.item = null;
        f.next = f; // help GC
        first = n;
        if (n == null)
            last = null;
        else
            n.prev = null;
        --count;
        notFull.signal();
        return item;
    }

    //移出尾节点,并将最后倒数第二个节点的下一个节点赋为空
    private E unlinkLast() {
        // assert lock.isHeldByCurrentThread();
        Node<E> l = last;
        if (l == null)
            return null;
        Node<E> p = l.prev;
        E item = l.item;
        l.item = null;
        l.prev = l; // help GC
        last = p;
        if (p == null)
            first = null;
        else
            p.next = null;
        --count;
        notFull.signal();
        return item;
    }

    //移除指定的节点
    void unlink(Node<E> x) {
        // assert lock.isHeldByCurrentThread();
        Node<E> p = x.prev;
        Node<E> n = x.next;
        //如果 没有上一个节点 那为头节点
        if (p == null) {
            unlinkFirst();
        //如果没有下一个节点为尾节点
        } else if (n == null) {
            unlinkLast();
        } else {
            //都不是就是需要去单独处理, p.的下一个节点指向 x的下一个节点
            p.next = n;
            n.prev = p;
            x.item = null;
            // Don't mess with x's links. They may still be in use by
            // an iterator.
            //总数减1 并唤醒等待线程
            --count;
            notFull.signal();
        }
    }

    // BlockingDeque methods

    //添加节点到首节点,失败则抛出异常
    public void addFirst(E e) {
        if (!offerFirst(e))
            throw new IllegalStateException("Deque full");
    }

    //添加节点到尾节点,失败则抛出异常
    public void addLast(E e) {
        if (!offerLast(e))
            throw new IllegalStateException("Deque full");
    }

    //添加节点到首节点,如果为空则抛出异常(带锁)
    public boolean offerFirst(E e) {
        if (e == null) throw new NullPointerException();
        Node<E> node = new Node<E>(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return linkFirst(node);
        } finally {
            lock.unlock();
        }
    }

    //添加节点到尾节点为空抛出异常(带锁)
    public boolean offerLast(E e) {
        if (e == null) throw new NullPointerException();
        Node<E> node = new Node<E>(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return linkLast(node);
        } finally {
            lock.unlock();
        }
    }

   //添加节点到首节点(如果已满则等待)
    public void putFirst(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();
        Node<E> node = new Node<E>(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            while (!linkFirst(node))
                notFull.await();
        } finally {
            lock.unlock();
        }
    }

    //添加节点到尾节点(如果已满则等待)
    public void putLast(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();
        Node<E> node = new Node<E>(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            while (!linkLast(node))
                notFull.await();
        } finally {
            lock.unlock();
        }
    }

    //带过期时间添加到首节点,如果超时则抓住败
    public boolean offerFirst(E e, long timeout, TimeUnit unit)
        throws InterruptedException {
        if (e == null) throw new NullPointerException();
        Node<E> node = new Node<E>(e);
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (!linkFirst(node)) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);
            }
            return true;
        } finally {
            lock.unlock();
        }
    }

    //带过期时间添加到尾节点(超时失败)
    public boolean offerLast(E e, long timeout, TimeUnit unit)
        throws InterruptedException {
        if (e == null) throw new NullPointerException();
        Node<E> node = new Node<E>(e);
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (!linkLast(node)) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);
            }
            return true;
        } finally {
            lock.unlock();
        }
    }

    //移除首节点一个数据(为空抛出异常)
    public E removeFirst() {
        E x = pollFirst();
        if (x == null) throw new NoSuchElementException();
        return x;
    }

    //移除最后一个节点并返回(为空抛出异常)
    public E removeLast() {
        E x = pollLast();
        if (x == null) throw new NoSuchElementException();
        return x;
    }
    //移除第一个节点并返回(带锁)
    public E pollFirst() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return unlinkFirst();
        } finally {
            lock.unlock();
        }
    }
    //移除最后一个节点并返回(带锁)
    public E pollLast() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return unlinkLast();
        } finally {
            lock.unlock();
        }
    }
    //移除第一个节点,如果为空则线程等待(带锁)
    public E takeFirst() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            E x;
            while ( (x = unlinkFirst()) == null)
                notEmpty.await();
            return x;
        } finally {
            lock.unlock();
        }
    }
    //移除最后一个节点(带锁)
    public E takeLast() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            E x;
            while ( (x = unlinkLast()) == null)
                notEmpty.await();
            return x;
        } finally {
            lock.unlock();
        }
    }
    //带过期时间 移除第一个节点(带锁)
    public E pollFirst(long timeout, TimeUnit unit)
        throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            E x;
            while ( (x = unlinkFirst()) == null) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            return x;
        } finally {
            lock.unlock();
        }
    }
    //带过期时间 移除最后一个节点(带锁)
    public E pollLast(long timeout, TimeUnit unit)
        throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            E x;
            while ( (x = unlinkLast()) == null) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            return x;
        } finally {
            lock.unlock();
        }
    }

    //移除第一个节点(如果为空抛出异常)
    public E getFirst() {
        E x = peekFirst();
        if (x == null) throw new NoSuchElementException();
        return x;
    }

    //移除最后一个节点(如果为空抛出异常)
    public E getLast() {
        E x = peekLast();
        if (x == null) throw new NoSuchElementException();
        return x;
    }
    //获取第一个节点(带锁)
    public E peekFirst() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (first == null) ? null : first.item;
        } finally {
            lock.unlock();
        }
    }
    //获取最后一个节点(带锁)
    public E peekLast() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (last == null) ? null : last.item;
        } finally {
            lock.unlock();
        }
    }
    //移除从头节点开始找与参数相同的节点 返回成功或失败(带锁)
    public boolean removeFirstOccurrence(Object o) {
        if (o == null) return false;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            //循环判断是否一致
            for (Node<E> p = first; p != null; p = p.next) {
                if (o.equals(p.item)) {
                    unlink(p);
                    return true;
                }
            }
            return false;
        } finally {
            lock.unlock();
        }
    }
        //移除从尾节点开始找与参数相同的节点 返回成功或失败(带锁)
    public boolean removeLastOccurrence(Object o) {
        if (o == null) return false;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            for (Node<E> p = last; p != null; p = p.prev) {
                if (o.equals(p.item)) {
                    unlink(p);
                    return true;
                }
            }
            return false;
        } finally {
            lock.unlock();
        }
    }

    //添加一个节点到队尾
    public boolean add(E e) {
        addLast(e);
        return true;
    }

   //添加一个节点到队列
    public boolean offer(E e) {
        return offerLast(e);
    }

   //添加一个节点到队尾,如果已满则等待
    public void put(E e) throws InterruptedException {
        putLast(e);
    }

    //带过期时间 添加一个节点到队尾
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {
        return offerLast(e, timeout, unit);
    }

    //移除首个节点并返回
    public E remove() {
        return removeFirst();
    }
    //移除首个节点并返回
    public E poll() {
        return pollFirst();
    }
    //带等待条件 移除首个节点并返回
    public E take() throws InterruptedException {
        return takeFirst();
    }
    //带过期时间 移除首个节点并返回
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        return pollFirst(timeout, unit);
    }

    //获取首个节点 为空抛出异常
    public E element() {
        return getFirst();
    }
    //获取首个节点
    public E peek() {
        return peekFirst();
    }

    //获取剩余容量(带锁)
    public int remainingCapacity() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return capacity - count;
        } finally {
            lock.unlock();
        }
    }

    //转成一个新列表
    public int drainTo(Collection<? super E> c) {
        return drainTo(c, Integer.MAX_VALUE);
    }

    //新实例表的实现
    public int drainTo(Collection<? super E> c, int maxElements) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        if (maxElements <= 0)
            return 0;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int n = Math.min(maxElements, count);
            for (int i = 0; i < n; i++) {
                c.add(first.item); // In this order, in case add() throws.
                unlinkFirst();
            }
            return n;
        } finally {
            lock.unlock();
        }
    }

    // Stack methods

    //添加一个节点到头节点
    public void push(E e) {
        addFirst(e);
    }

    //移除第一个节点 并返回
    public E pop() {
        return removeFirst();
    }

    // Collection methods

   //从队列中移到与节点相同的首个对象
    public boolean remove(Object o) {
        return removeFirstOccurrence(o);
    }

   //当前队列大小
    public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }

    //判断队列是否拥有该节点
    public boolean contains(Object o) {
        if (o == null) return false;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            for (Node<E> p = first; p != null; p = p.next)
                if (o.equals(p.item))
                    return true;
            return false;
        } finally {
            lock.unlock();
        }
    }

   //将队列转成数组返回
    @SuppressWarnings("unchecked")
    public Object[] toArray() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] a = new Object[count];
            int k = 0;
            for (Node<E> p = first; p != null; p = p.next)
                a[k++] = p.item;
            return a;
        } finally {
            lock.unlock();
        }
    }

    //同上类似
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (a.length < count)
                a = (T[])java.lang.reflect.Array.newInstance
                    (a.getClass().getComponentType(), count);

            int k = 0;
            for (Node<E> p = first; p != null; p = p.next)
                a[k++] = (T)p.item;
            if (a.length > k)
                a[k] = null;
            return a;
        } finally {
            lock.unlock();
        }
    }
    //转成字符串
    public String toString() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Node<E> p = first;
            if (p == null)
                return "[]";

            StringBuilder sb = new StringBuilder();
            sb.append('[');
            for (;;) {
                E e = p.item;
                sb.append(e == this ? "(this Collection)" : e);
                p = p.next;
                if (p == null)
                    return sb.append(']').toString();
                sb.append(',').append(' ');
            }
        } finally {
            lock.unlock();
        }
    }

    //清空队列方法
    public void clear() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            for (Node<E> f = first; f != null; ) {
                f.item = null;
                Node<E> n = f.next;
                f.prev = null;
                f.next = null;
                f = n;
            }
            first = last = null;
            count = 0;
            notFull.signalAll();
        } finally {
            lock.unlock();
        }
    }
    //获取一个新的迭代器
    public Iterator<E> iterator() {
        return new Itr();
    }

   //将队列以相返顺序返回到迭代器中
    public Iterator<E> descendingIterator() {
        return new DescendingItr();
    }

    //迭代器基础类
    private abstract class AbstractItr implements Iterator<E> {
        //下一个节点
        Node<E> next;

        //下一个节点
        E nextItem;

        //最后一个节点
        private Node<E> lastRet;
        //首个节点
        abstract Node<E> firstNode();
        //下一个节眯抽象实现
        abstract Node<E> nextNode(Node<E> n);
        //构造方法
        AbstractItr() {
            // set to initial position
            final ReentrantLock lock = LinkedBlockingDeque.this.lock;
            lock.lock();
            try {
                next = firstNode();
                nextItem = (next == null) ? null : next.item;
            } finally {
                lock.unlock();
            }
        }

        //返回非空(包含已删除)的节点
        private Node<E> succ(Node<E> n) {
            // Chains of deleted nodes ending in null or self-links
            // are possible if multiple interior nodes are removed.
            for (;;) {
                Node<E> s = nextNode(n);
                if (s == null)
                    return null;
                else if (s.item != null)
                    return s;
                else if (s == n)
                    return firstNode();
                else
                    n = s;
            }
        }

        //下一个节点
        void advance() {
            final ReentrantLock lock = LinkedBlockingDeque.this.lock;
            lock.lock();
            try {
                // assert next != null;
                next = succ(next);
                nextItem = (next == null) ? null : next.item;
            } finally {
                lock.unlock();
            }
        }
        //判断是否拥有下一个节点
        public boolean hasNext() {
            return next != null;
        }
        //获取下一个节点
        public E next() {
            if (next == null)
                throw new NoSuchElementException();
            lastRet = next;
            E x = nextItem;
            advance();
            return x;
        }
        //移除一个节点
        public void remove() {
            Node<E> n = lastRet;
            if (n == null)
                throw new IllegalStateException();
            lastRet = null;
            final ReentrantLock lock = LinkedBlockingDeque.this.lock;
            lock.lock();
            try {
                if (n.item != null)
                    unlink(n);
            } finally {
                lock.unlock();
            }
        }
    }

    /** Forward iterator */
    private class Itr extends AbstractItr {
        Node<E> firstNode() { return first; }
        Node<E> nextNode(Node<E> n) { return n.next; }
    }

    /** Descending iterator */
    private class DescendingItr extends AbstractItr {
        Node<E> firstNode() { return last; }
        Node<E> nextNode(Node<E> n) { return n.prev; }
    }

    //自定义实现迭代器
    static final class LBDSpliterator<E> implements Spliterator<E> {
        static final int MAX_BATCH = 1 << 25; // max batch array size;
        final LinkedBlockingDeque<E> queue;
        Node<E> current; // current node; null until initialized
        int batch; // batch size for splits
        boolean exhausted; // true when no more nodes
        long est; // size estimate
        LBDSpliterator(LinkedBlockingDeque<E> queue) {
            this.queue = queue;
            this.est = queue.size();
        }

        public long estimateSize() { return est; }

        public Spliterator<E> trySplit() {
            Node<E> h;
            final LinkedBlockingDeque<E> q = this.queue;
            int b = batch;
            int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
            if (!exhausted &&
                ((h = current) != null || (h = q.first) != null) &&
                h.next != null) {
                Object[] a = new Object[n];
                final ReentrantLock lock = q.lock;
                int i = 0;
                Node<E> p = current;
                lock.lock();
                try {
                    if (p != null || (p = q.first) != null) {
                        do {
                            if ((a[i] = p.item) != null)
                                ++i;
                        } while ((p = p.next) != null && i < n);
                    }
                } finally {
                    lock.unlock();
                }
                if ((current = p) == null) {
                    est = 0L;
                    exhausted = true;
                }
                else if ((est -= i) < 0L)
                    est = 0L;
                if (i > 0) {
                    batch = i;
                    return Spliterators.spliterator
                        (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
                         Spliterator.CONCURRENT);
                }
            }
            return null;
        }
        //
        public void forEachRemaining(Consumer<? super E> action) {
            if (action == null) throw new NullPointerException();
            final LinkedBlockingDeque<E> q = this.queue;
            final ReentrantLock lock = q.lock;
            if (!exhausted) {
                exhausted = true;
                Node<E> p = current;
                do {
                    E e = null;
                    lock.lock();
                    try {
                        if (p == null)
                            p = q.first;
                        while (p != null) {
                            e = p.item;
                            p = p.next;
                            if (e != null)
                                break;
                        }
                    } finally {
                        lock.unlock();
                    }
                    if (e != null)
                        action.accept(e);
                } while (p != null);
            }
        }
        //向前挪动方法
        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null) throw new NullPointerException();
            final LinkedBlockingDeque<E> q = this.queue;
            final ReentrantLock lock = q.lock;
            if (!exhausted) {
                E e = null;
                lock.lock();
                try {
                    if (current == null)
                        current = q.first;
                    while (current != null) {
                        e = current.item;
                        current = current.next;
                        if (e != null)
                            break;
                    }
                } finally {
                    lock.unlock();
                }
                if (current == null)
                    exhausted = true;
                if (e != null) {
                    action.accept(e);
                    return true;
                }
            }
            return false;
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.NONNULL |
                Spliterator.CONCURRENT;
        }
    }

    /**
     * Returns a {@link Spliterator} over the elements in this deque.
     *
     * <p>The returned spliterator is
     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
     *
     * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
     * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
     *
     * @implNote
     * The {@code Spliterator} implements {@code trySplit} to permit limited
     * parallelism.
     *
     * @return a {@code Spliterator} over the elements in this deque
     * @since 1.8
     */
    public Spliterator<E> spliterator() {
        return new LBDSpliterator<E>(this);
    }

   //将数据流写到对象中
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            // Write out capacity and any hidden stuff
            s.defaultWriteObject();
            // Write out all elements in the proper order.
            for (Node<E> p = first; p != null; p = p.next)
                s.writeObject(p.item);
            // Use trailing null as sentinel
            s.writeObject(null);
        } finally {
            lock.unlock();
        }
    }

   //将数据流添加到列表中
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        count = 0;
        first = null;
        last = null;
        // Read in all elements and place in queue
        for (;;) {
            @SuppressWarnings("unchecked")
            E item = (E)s.readObject();
            if (item == null)
                break;
            add(item);
        }
    }

}

最后

    看了aqs里面这些阻塞队列,最大的收获是这个双向链表非常灵活,上下节点都在指向中,很容易可以获取到,并且所有的操作基本都有aqs锁的加持所以基本都是线程安全的,还有一个在使用上要特别注意有大量的空等待,如果没有带过期时间或者说不熟悉可能引发生产的事故,所以在使用上时要特别注意,这里又让我想起现在公司与以前的公司很多同学在使用这个blocking队列的时候往往都忽视这点,而到头来搞了一个生产事故还说人家设计的不好,想想都历历在目,真是无语~。当然本文基于本人下班后有空进行一行一行看,有些可能写的不详细或有误,请自行查阅对比,有需要深入同学可以看看并发包个路径下还有大量的类,可以进去调试学习。

参考文章:

    https://www.cnblogs.com/bjxq-cs88/p/9759571.html

    https://jenkov.com/tutorials/java-concurrency/index.html

    https://juejin.cn/post/6968795388685844488

猜你喜欢

转载自blog.csdn.net/qq_16498553/article/details/128280970