阻塞队列—PriorityBlockingQueue源码分析

开发 前端
PriorityBlockingQueue 优先级队列,线程安全(添加、读取都进行了加锁)、无界、读阻塞的队列,底层采用的堆结构实现(二叉树),默认是小根堆,最小的或者最大的元素会一直置顶,每次获取都取最顶端的数据

 前言


PriorityBlockingQueue 优先级队列,线程安全(添加、读取都进行了加锁)、无界、读阻塞的队列,底层采用的堆结构实现(二叉树),默认是小根堆,最小的或者最大的元素会一直置顶,每次获取都取最顶端的数据

队列创建

小根堆

  1. PriorityBlockingQueue<Integer> concurrentLinkedQueue = new PriorityBlockingQueue<Integer>(); 

大根堆

  1. PriorityBlockingQueue<Integer> concurrentLinkedQueue = new PriorityBlockingQueue<Integer>(10, new Comparator<Integer>() { 
  2.  @Override 
  3.  public int compare(Integer o1, Integer o2) { 
  4.   return o2 - o1; 
  5.  } 
  6. }); 

 应用场景

有任务要执行,可以对任务加一个优先级的权重,这样队列会识别出来,对该任务优先进行出队。

我们来看一个具体例子,例子中定义了一个将要放入“优先阻塞队列”的任务类,并且定义了一个任务工场类和一个任务执行类,在任务工场类中产生了各种不同优先级的任务,将其添加到队列中,在任务执行类中,任务被一个个取出并执行。

  1. package com.niuh.queue.priority; 
  2.  
  3. import java.util.ArrayList; 
  4. import java.util.List; 
  5. import java.util.Queue; 
  6. import java.util.Random; 
  7. import java.util.concurrent.ExecutorService; 
  8. import java.util.concurrent.Executors; 
  9. import java.util.concurrent.PriorityBlockingQueue; 
  10. import java.util.concurrent.TimeUnit; 
  11.  
  12. /** 
  13.  * <p> 
  14.  * PriorityBlockingQueue使用示例 
  15.  * </p> 
  16.  */ 
  17. public class PriorityBlockingQueueDemo { 
  18.  
  19.     public static void main(String[] args) throws Exception { 
  20.         Random random = new Random(47); 
  21.         ExecutorService exec = Executors.newCachedThreadPool(); 
  22.         PriorityBlockingQueue<Runnable> queue = new PriorityBlockingQueue<>(); 
  23.         exec.execute(new PrioritizedTaskProducer(queue, exec)); // 这里需要注意,往PriorityBlockingQueue中添加任务和取出任务的 
  24.         exec.execute(new PrioritizedTaskConsumer(queue)); // 步骤是同时进行的,因而输出结果并不一定是有序的 
  25.     } 
  26.  
  27. class PrioritizedTask implements Runnable, Comparable<PrioritizedTask> { 
  28.     private Random random = new Random(47); 
  29.     private static int counter = 0; 
  30.     private final int id = counter++; 
  31.     private final int priority; 
  32.  
  33.     protected static List<PrioritizedTask> sequence = new ArrayList<>(); 
  34.  
  35.     public PrioritizedTask(int priority) { 
  36.         this.priority = priority; 
  37.         sequence.add(this); 
  38.     } 
  39.  
  40.     @Override 
  41.     public int compareTo(PrioritizedTask o) { 
  42.         return priority < o.priority ? 1 : (priority > o.priority ? -1 : 0);  // 定义优先级计算方式 
  43.     } 
  44.  
  45.     @Override 
  46.     public void run() { 
  47.         try { 
  48.             TimeUnit.MILLISECONDS.sleep(random.nextInt(250)); 
  49.         } catch (InterruptedException e) { 
  50.         } 
  51.         System.out.println(this); 
  52.     } 
  53.  
  54.     @Override 
  55.     public String toString() { 
  56.         return String.format("[%1$-3d]", priority) + " Task " + id; 
  57.     } 
  58.  
  59.     public String summary() { 
  60.         return "(" + id + ": " + priority + ")"
  61.     } 
  62.  
  63.     public static class EndSentinel extends PrioritizedTask { 
  64.         private ExecutorService exec
  65.  
  66.         public EndSentinel(ExecutorService exec) { 
  67.             super(-1); 
  68.             this.exec = exec
  69.         } 
  70.  
  71.         @Override 
  72.         public void run() { 
  73.             int count = 0; 
  74.             for (PrioritizedTask pt : sequence) { 
  75.                 System.out.print(pt.summary()); 
  76.                 if (++count % 5 == 0) { 
  77.                     System.out.println(); 
  78.                 } 
  79.             } 
  80.             System.out.println(); 
  81.             System.out.println(this + " Calling shutdownNow()"); 
  82.             exec.shutdownNow(); 
  83.         } 
  84.     } 
  85.  
  86. class PrioritizedTaskProducer implements Runnable { 
  87.     private Random random = new Random(47); 
  88.     private Queue<Runnable> queue; 
  89.     private ExecutorService exec
  90.  
  91.     public PrioritizedTaskProducer(Queue<Runnable> queue, ExecutorService exec) { 
  92.         this.queue = queue; 
  93.         this.exec = exec
  94.     } 
  95.  
  96.     @Override 
  97.     public void run() { 
  98.         for (int i = 0; i < 20; i++) { 
  99.             queue.add(new PrioritizedTask(random.nextInt(10))); // 往PriorityBlockingQueue中添加随机优先级的任务 
  100.             Thread.yield(); 
  101.         } 
  102.         try { 
  103.             for (int i = 0; i < 10; i++) { 
  104.                 TimeUnit.MILLISECONDS.sleep(250); 
  105.                 queue.add(new PrioritizedTask(10)); // 往PriorityBlockingQueue中添加优先级为10的任务 
  106.             } 
  107.             for (int i = 0; i < 10; i++) { 
  108.                 queue.add(new PrioritizedTask(i));// 往PriorityBlockingQueue中添加优先级为1-10的任务 
  109.             } 
  110.             queue.add(new PrioritizedTask.EndSentinel(exec)); 
  111.         } catch (InterruptedException e) { 
  112.         } 
  113.         System.out.println("Finished PrioritizedTaskProducer"); 
  114.     } 
  115.  
  116. class PrioritizedTaskConsumer implements Runnable { 
  117.     private PriorityBlockingQueue<Runnable> queue; 
  118.  
  119.     public PrioritizedTaskConsumer(PriorityBlockingQueue<Runnable> queue) { 
  120.         this.queue = queue; 
  121.     } 
  122.  
  123.     @Override 
  124.     public void run() { 
  125.         try { 
  126.             while (!Thread.interrupted()) { 
  127.                 queue.take().run(); // 任务的消费者,从PriorityBlockingQueue中取出任务执行 
  128.             } 
  129.         } catch (InterruptedException e) { 
  130.         } 
  131.         System.out.println("Finished PrioritizedTaskConsumer"); 
  132.     } 

 工作原理

PriorityBlockingQueue 是 JDK1.5 的时候出来的一个阻塞队列。但是该队列入队的时候是不会阻塞的,永远会加到队尾。下面我们介绍下它的几个特点:

  • PriorityBlockingQueue 和 ArrayBlockingQueue 一样是基于数组实现的,但后者在初始化时需要指定长度,前者默认长度是 11。
  • 该队列可以说是真正的无界队列,它在队列满的时候会进行扩容,而前面说的无界阻塞队列其实都有有界,只是界限太大可以忽略(最大值是 2147483647)
  • 该队列属于权重队列,可以理解为它可以进行排序,但是排序不是从小到大排或从大到小排,是基于数组的堆结构(具体如何排下面会进行分析)
  • 出队方式和前面的也不同,是根据权重来进行出队,和前面所说队列中那种先进先出或者先进后出方式不同。
  • 其存入的元素必须实现Comparator,或者在创建队列的时候自定义Comparator。

注意:

  1. 堆结构实际上是一种完全二叉树。关于二叉树可以查看 《树、二叉树、二叉搜索树的实现和特性》
  2. 堆又分为大顶堆和小顶堆 。大顶堆中第一个元素肯定是所有元素中最大的,小顶堆中第一个元素是所有元素中最小的。关于二叉堆可以查看《堆和二叉堆的实现和特性》

源码分析

定义

PriorityBlockingQueue的类继承关系如下:

其包含的方法定义如下:

成员属性

从下面的字段我们可以知道,该队列可以排序,使用显示锁来保证操作的原子性,在空队列时,出队线程会堵塞等。 

  1. /** 
  2. * 默认数组长度 
  3. */ 
  4. private static final int DEFAULT_INITIAL_CAPACITY = 11; 
  5.  
  6. /** 
  7.  * 最大达容量,分配时超出可能会出现 OutOfMemoryError 异常 
  8.  */ 
  9. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; 
  10.  
  11. /** 
  12.  * 队列,存储我们的元素 
  13.  */ 
  14. private transient Object[] queue; 
  15.  
  16. /** 
  17.  * 队列长度 
  18.  */ 
  19. private transient int size
  20.  
  21. /** 
  22.  * 比较器,入队进行权重的比较 
  23.  */ 
  24. private transient Comparator<? super E> comparator; 
  25.  
  26. /** 
  27.  * 显示锁 
  28.  */ 
  29. private final ReentrantLock lock; 
  30.  
  31. /** 
  32.  * 空队列时进行线程阻塞的 Condition 对象 
  33.  */ 
  34. private final Condition notEmpty; 

 构造函数 

  1. /** 
  2. * 默认构造,使用长度为 11 的数组,比较器为空 
  3. */ 
  4. public PriorityBlockingQueue() { 
  5.     this(DEFAULT_INITIAL_CAPACITY, null); 
  6. /** 
  7. * 自定义数据长度构造,比较器为空 
  8. */ 
  9. public PriorityBlockingQueue(int initialCapacity) { 
  10.     this(initialCapacity, null); 
  11. /** 
  12. * 自定义数组长度,可以自定义比较器 
  13. */ 
  14. public PriorityBlockingQueue(int initialCapacity, 
  15.                              Comparator<? super E> comparator) { 
  16.     if (initialCapacity < 1) 
  17.         throw new IllegalArgumentException(); 
  18.     this.lock = new ReentrantLock(); 
  19.     this.notEmpty = lock.newCondition(); 
  20.     this.comparator = comparator; 
  21.     this.queue = new Object[initialCapacity]; 
  22. /** 
  23. * 构造函数,带有初始内容的队列 
  24. */ 
  25. public PriorityBlockingQueue(Collection<? extends E> c) { 
  26.     this.lock = new ReentrantLock(); 
  27.     this.notEmpty = lock.newCondition(); 
  28.     boolean heapify = true; // true if not known to be in heap order 
  29.     boolean screen = true;  // true if must screen for nulls 
  30.     if (c instanceof SortedSet<?>) { 
  31.         SortedSet<? extends E> ss = (SortedSet<? extends E>) c; 
  32.         this.comparator = (Comparator<? super E>) ss.comparator(); 
  33.         heapify = false
  34.     } 
  35.     else if (c instanceof PriorityBlockingQueue<?>) { 
  36.         PriorityBlockingQueue<? extends E> pq = 
  37.             (PriorityBlockingQueue<? extends E>) c; 
  38.         this.comparator = (Comparator<? super E>) pq.comparator(); 
  39.         screen = false
  40.         if (pq.getClass() == PriorityBlockingQueue.class) // exact match 
  41.             heapify = false
  42.     } 
  43.     Object[] a = c.toArray(); 
  44.     int n = a.length; 
  45.     // If c.toArray incorrectly doesn't return Object[], copy it. 
  46.     if (a.getClass() != Object[].class) 
  47.         a = Arrays.copyOf(a, n, Object[].class); 
  48.     if (screen && (n == 1 || this.comparator != null)) { 
  49.         for (int i = 0; i < n; ++i) 
  50.             if (a[i] == null
  51.                 throw new NullPointerException(); 
  52.     } 
  53.     this.queue = a; 
  54.     this.size = n; 
  55.     if (heapify) 
  56.         heapify(); 

 入队方法

入队方法,下面可以看到 put 方法最终会调用 offer 方法,所以我们只看 offer 方法即可。

offer(E e)

  1. public void put(E e) { 
  2.     offer(e); // never need to block 
  3.  
  4. public boolean offer(E e) { 
  5.     //判断是否为空 
  6.     if (e == null
  7.         throw new NullPointerException(); 
  8.     //显示锁 
  9.     final ReentrantLock lock = this.lock; 
  10.     lock.lock(); 
  11.     //定义临时对象 
  12.     int n, cap; 
  13.     Object[] array; 
  14.     //判断数组是否满了 
  15.     while ((n = size) >= (cap = (array = queue).length)) 
  16.         //数组扩容 
  17.         tryGrow(array, cap); 
  18.     try { 
  19.         //拿到比较器 
  20.         Comparator<? super E> cmp = comparator; 
  21.         //判断是否有自定义比较器 
  22.         if (cmp == null
  23.             //堆上浮 
  24.             siftUpComparable(n, e, array); 
  25.         else 
  26.             //使用自定义比较器进行堆上浮 
  27.             siftUpUsingComparator(n, e, array, cmp); 
  28.         //队列长度 +1 
  29.         size = n + 1; 
  30.         //唤醒休眠的出队线程 
  31.         notEmpty.signal(); 
  32.     } finally { 
  33.         //释放锁 
  34.         lock.unlock(); 
  35.     } 
  36.     return true

 siftUpComparable(int k, T x, Object[] array)

上浮调整比较器方法的实现

  1. private static <T> void siftUpComparable(int k, T x, Object[] array) { 
  2.         Comparable<? super T> key = (Comparable<? super T>) x; 
  3.         while (k > 0) { 
  4.          //无符号向左移,目的是找到放入位置的父节点 
  5.             int parent = (k - 1) >>> 1; 
  6.             //拿到父节点的值 
  7.             Object e = array[parent]; 
  8.             //比较是否大于该元素,不大于就没比较交换 
  9.             if (key.compareTo((T) e) >= 0) 
  10.                 break; 
  11.             //以下都是元素位置交换 
  12.             array[k] = e; 
  13.             k = parent; 
  14.         } 
  15.         array[k] = key
  16.     } 

 根据上面的代码,可以看出这是完全二叉树在进行上浮调整。调整入队的元素,找出最小的,将元素排列有序化。简单理解就是:父节点元素值一定要比它的子节点得小,如果父节点大于子节点了,那就两者位置进行交换。

入队图解

例子:85 添加到二叉堆中(大顶堆)

  1. package com.niuh.queue.priority; 
  2.  
  3. import java.util.Comparator; 
  4. import java.util.concurrent.PriorityBlockingQueue; 
  5.  
  6. /** 
  7.  * <p> 
  8.  * PriorityBlockingQueue 简单演示 demo 
  9.  * </p> 
  10.  */ 
  11. public class TestPriorityBlockingQueue { 
  12.  
  13.     public static void main(String[] args) throws InterruptedException { 
  14.         // 大顶堆 
  15.         PriorityBlockingQueue<Integer> concurrentLinkedQueue = new PriorityBlockingQueue<Integer>(10, new Comparator<Integer>() { 
  16.             @Override 
  17.             public int compare(Integer o1, Integer o2) { 
  18.                 return o2 - o1; 
  19.             } 
  20.         }); 
  21.  
  22.         concurrentLinkedQueue.offer(90); 
  23.         concurrentLinkedQueue.offer(80); 
  24.         concurrentLinkedQueue.offer(70); 
  25.         concurrentLinkedQueue.offer(60); 
  26.         concurrentLinkedQueue.offer(40); 
  27.         concurrentLinkedQueue.offer(30); 
  28.         concurrentLinkedQueue.offer(20); 
  29.         concurrentLinkedQueue.offer(10); 
  30.         concurrentLinkedQueue.offer(50); 
  31.         concurrentLinkedQueue.offer(85); 
  32.         //输出元素排列 
  33.         concurrentLinkedQueue.stream().forEach(e-> System.out.print(e+"  ")); 
  34.         //取出元素 
  35.         Integer take = concurrentLinkedQueue.take(); 
  36.         System.out.println(); 
  37.         concurrentLinkedQueue.stream().forEach(e-> System.out.print(e+"  ")); 
  38.     } 

 

操作的细节分为两步:

  • 第一步:首先把新元素插入到堆的尾部再说;(新的元素可能是特别大或者特别小,那么要做的一件事情就是重新维护一下堆的所有元素,把新元素挪到这个堆的相应的位置)
  • 第二步:依次向上调整整个堆的结构,就叫 HeapifyUp

  

 85 按照上面讲的先插入到堆的尾部,也就是一维数组的尾部,一维数组的尾部的话就上图的位置,因为这是一个完全二叉树,所以它的尾部就是50后面这个结点。插进来之后这个时候就破坏了堆,它的每一个结点都要大于它的儿子的这种属性了,接下来要做的事情就是要把 85 依次地向上浮动,怎么浮动?就是 85 大于它的父亲结点,那么就和父亲结点进行交换,直到走到根如果大于根的话,就和根也进行交换。


85 再继续往前走之后,它要和 80 再进行比较,同理可得:也就是说这个结点每次和它的父亲比,如果它大于它的父亲的话就交换,直到它不再大于它的父亲。

 

出队方法

入队列的方法说完后,我们来说说出队列的方法。PriorityBlockingQueue提供了多种出队操作的实现来满足不同情况下的需求,如下:

  • E take();
  • E poll();
  • E poll(long timeout, TimeUnit unit);
  • E peek()

poll 和 peek 与上面类似,这里不做说明

take()

出队方法,该方法会阻塞

  1. public E take() throws InterruptedException { 
  2.  //显示锁 
  3.     final ReentrantLock lock = this.lock; 
  4.     //可中断锁 
  5.     lock.lockInterruptibly(); 
  6.     //结果接收对象 
  7.     E result; 
  8.     try { 
  9.      //判断队列是否为空 
  10.         while ( (result = dequeue()) == null
  11.          //线程阻塞 
  12.             notEmpty.await(); 
  13.     } finally { 
  14.         lock.unlock(); 
  15.     } 
  16.     return result; 

 dequeue()

我们再来看看具体出队方法的实现,dequeue方法

  1. private E dequeue() { 
  2. //长度减少 1 
  3.    int n = size - 1; 
  4.    //判断队列中是否有元素 
  5.    if (n < 0) 
  6.        return null
  7.    else { 
  8.     //队列对象 
  9.        Object[] array = queue; 
  10.        //取出第一个元素 
  11.        E result = (E) array[0]; 
  12.        //拿出最后一个元素 
  13.        E x = (E) array[n]; 
  14.        //置空 
  15.        array[n] = null
  16.        Comparator<? super E> cmp = comparator; 
  17.        if (cmp == null
  18.         //下沉调整 
  19.            siftDownComparable(0, x, array, n); 
  20.        else 
  21.            siftDownUsingComparator(0, x, array, n, cmp); 
  22.        //成功则减少队列中的元素数量 
  23.        size = n; 
  24.        return result; 
  25.    } 

 总体就是找到父节点与两个子节点中最小的一个节点,然后进行交换位置,不断重复,由上而下的交换。

siftDownComparable(int k, T x, Object[] array, int n)

再来看看下沉比较器方法的实现

  1. private static <T> void siftDownComparable(int k, T x, Object[] array, 
  2.                                                int n) { 
  3.     //判断队列长度 
  4.     if (n > 0) { 
  5.         Comparable<? super T> key = (Comparable<? super T>)x; 
  6.         //找到队列最后一个元素的父节点的索引。 
  7.         int half = n >>> 1;           // loop while a non-leaf 
  8.         while (k < half) { 
  9.          //拿到 k 节点下的左子节点 
  10.             int child = (k << 1) + 1; // assume left child is least 
  11.             //取得子节点对应的值 
  12.             Object c = array[child]; 
  13.             //取得 k 右子节点的索引 
  14.             int right = child + 1; 
  15.             //比较右节点的索引是否小于队列长度和左右子节点的值进行比较 
  16.             if (right < n && 
  17.                 ((Comparable<? super T>) c).compareTo((T) array[right]) > 0) 
  18.                 c = array[child = right]; 
  19.             //比较父节点值是否大于子节点 
  20.             if (key.compareTo((T) c) <= 0) 
  21.                 break; 
  22.             //下面都是元素替换 
  23.             array[k] = c; 
  24.             k = child; 
  25.         } 
  26.         array[k] = key
  27.     } 

 出队图解

将堆尾元素替换到顶部(即堆顶被替代删除掉)

依次从根部向下调整整个堆的结构(一直到堆尾即可) HeapifyDown

例子:90 从二叉堆中删除(大顶堆)


总结

PriorityBlockingQueue 真的是个神奇的队列,可以实现优先出队。最特别的是它只有一个锁,入队操作永远成功,而出队只有在空队列的时候才会进行线程阻塞。可以说有一定的应用场景吧,比如:有任务要执行,可以对任务加一个优先级的权重,这样队列会识别出来,对该任务优先进行出队。

 

责任编辑:姜华 来源: 今日头条
相关推荐

2020-11-19 07:41:51

ArrayBlocki

2020-11-25 14:28:56

DelayedWork

2020-11-20 06:22:02

LinkedBlock

2017-04-12 10:02:21

Java阻塞队列原理分析

2012-06-14 10:34:40

Java阻塞搜索实例

2023-12-28 07:49:11

线程池源码应用场景

2023-12-15 09:45:21

阻塞接口

2022-06-30 08:14:05

Java阻塞队列

2021-06-04 14:15:10

鸿蒙HarmonyOS应用

2024-02-20 08:16:10

阻塞队列源码

2021-09-22 14:36:32

鸿蒙HarmonyOS应用

2023-12-05 13:46:09

解密协程线程队列

2014-08-26 11:11:57

AsyncHttpCl源码分析

2011-03-15 11:33:18

iptables

2021-01-09 13:57:05

阻塞队列并发

2020-11-27 09:16:21

BlockingQue

2022-06-30 14:31:57

Java阻塞队列

2021-05-12 09:45:20

鸿蒙HarmonyOS应用

2011-05-26 10:05:48

MongoDB

2021-04-07 15:11:26

鸿蒙HarmonyOS应用
点赞
收藏

51CTO技术栈公众号