日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java Review - 并发编程_PriorityBlockingQueue原理源码剖析

發布時間:2025/3/21 java 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java Review - 并发编程_PriorityBlockingQueue原理源码剖析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 概述
  • 類圖結構
  • 小Demo
  • 核心方法&源碼解析
    • offer
    • poll
    • put
    • take
    • size


概述

PriorityBlockingQueue是帶優先級的無界阻塞隊列,每次出隊都返回優先級最高或者最低的元素。

其內部是使用平衡二叉樹堆實現的,所以直接遍歷隊列元素不保證有序。

默認使用對象的compareTo方法提供比較規則,如果你需要自定義比較規則則可以自定義comparators。

類圖結構


由圖可知,

  • PriorityBlockingQueue內部有一個數組queue,用來存放隊列元素,size用來存放隊列元素個數。

  • allocationSpinLock是個自旋鎖,其使用CAS操作來保證同時只有一個線程可以擴容隊列,狀態為0或者1,其中0表示當前沒有進行擴容,1表示當前正在擴容。

  • 由于這是一個優先級隊列,所以有一個比較器comparator用來比較元素大小。

  • lock獨占鎖對象用來控制同時只能有一個線程可以進行入隊、出隊操作。

  • notEmpty條件變量用來實現take方法阻塞模式。這里沒有notFull 條件變量是因為這里的put操作是非阻塞的,為啥要設計為非阻塞的,是因為這是無界隊列。

  • 在如下構造函數中,默認隊列容量為11,默認比較器為null,也就是使用元素的compareTo方法進行比較來確定元素的優先級,這意味著隊列元素必須實現了Comparable接口。

/*** Default array capacity.*/private static final int DEFAULT_INITIAL_CAPACITY = 11;/*** Creates a {@code PriorityBlockingQueue} with the default* initial capacity (11) that orders its elements according to* their {@linkplain Comparable natural ordering}.*/public PriorityBlockingQueue() {this(DEFAULT_INITIAL_CAPACITY, null);}/*** Creates a {@code PriorityBlockingQueue} with the specified* initial capacity that orders its elements according to their* {@linkplain Comparable natural ordering}.** @param initialCapacity the initial capacity for this priority queue* @throws IllegalArgumentException if {@code initialCapacity} is less* than 1*/public PriorityBlockingQueue(int initialCapacity) {this(initialCapacity, null);}/*** Creates a {@code PriorityBlockingQueue} with the specified initial* capacity that orders its elements according to the specified* comparator.** @param initialCapacity the initial capacity for this priority queue* @param comparator the comparator that will be used to order this* priority queue. If {@code null}, the {@linkplain Comparable* natural ordering} of the elements will be used.* @throws IllegalArgumentException if {@code initialCapacity} is less* than 1*/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];}


小Demo

先搞個Demo體會PriorityBlockingQueue的使用方法。在這個Demo中,會把具有優先級的任務放入隊列,然后從隊列里面逐個獲取優先級最高的任務來執行


核心方法&源碼解析

offer

poll

put

take

size

總結

以上是生活随笔為你收集整理的Java Review - 并发编程_PriorityBlockingQueue原理源码剖析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。