简介
PriorityBlockingQueue :优先级阻塞队列,即已谁优先谁先出的模式。
既然具有优先级,那么必然元素需要实现Comparable
PriorityBlockingQueue 是可视为一个无边界队列(只要不超出Integer.MAX_VALUE - 8),基于堆排序
初始化
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;
//默认容量为8
this.queue = new Object[initialCapacity];
}
public PriorityBlockingQueue(Collection<? extends E> c) {
this.lock = new ReentrantLock();
this.notEmpty = lock.newCondition();
//是否需要进行构造堆
boolean heapify = true;
//是否需要判断null
boolean screen = true;
//如果是SortedSet 说明是有序的
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();
//不需要进行null判断
screen = false;
if (pq.getClass() == PriorityBlockingQueue.class) // exact match
//不需要构造堆
heapify = false;
}
Object[] a = c.toArray();
int n = a.length;
//进行复制
if (a.getClass() != Object[].class)
a = Arrays.copyOf(a, n, Object[].class);
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 heapify() {
Object[] array = queue;
int n = size;
//n/2-1 开始 (二叉树的最后一个父节点)
int half = (n >>> 1) - 1;
Comparator<? super E> cmp = comparator;
if (cmp == null) {
//如果比较器为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);
}
}
//最小堆排序 了解堆排序应该很好理解
private static <T> void siftDownComparable(int k, T x, Object[] array,
int n) {
if (n > 0) {
Comparable<? super T> key = (Comparable<? super T>)x;
int half = n >>> 1; // loop while a non-leaf
//当前k不能超过n/2
while (k < half) {
//k的左 为k/2+1 右为k/2+2
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];
if (key.compareTo((T) c) <= 0)
break;
//将c赋给k位置
array[k] = c;
//k变成child 再次循环 直到break
k = child;
}
//将最终的key赋给k位置
array[k] = key;
}
}
//和siftDownComparable 类似 只是比较器用的是初始化的比较器
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 tryGrow(Object[] array, int oldCap) {
//先释放主锁 保证获取正常
lock.unlock();
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);
}
}
//add put 都是调用offer
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 boolean offer(E e, long timeout, TimeUnit unit) {
return offer(e); // never need to block
}
//入队操作 确定最后一个位置的值
private static <T> void siftUpComparable(int k, T x, Object[] array) {
Comparable<? super T> key = (Comparable<? super T>) x;
while (k > 0) {
//最小值为0 对应while 从二叉树的最后一个父节点开始 一直往上直至0进行对比
int parent = (k - 1) >>> 1;
Object e = array[parent];
if (key.compareTo((T) e) >= 0)
break;
array[k] = e;
k = parent;
}
array[k] = key;
}
//和siftUpComparable类似
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 E dequeue() {
int n = size - 1;
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;
//还是熟悉的siftDownComparable方法 直接确定0位置值
if (cmp == null)
siftDownComparable(0, x, array, n);
else
siftDownUsingComparator(0, x, array, n, cmp);
size = n;
return result;
}
}
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;
}
//过期时间内无值则返回null
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();
}
}
总结
优先队列 相对其他队列来说, 具有对比排序的功能,也可以根据自己需求增加自己的比较器进行排序。其中DelayQueue中使用了优选队列,所以DelayQueue拥有排序功能!
当然因为不管是出队还是入队,都需要进行排序,所以效率上来讲不如ArrayBlockingQueue,但是如果需要排序队列的需求,优选PriorityBlockingQueue