介绍
一个支持线程优先级排序的无界队列,默认自然序进行排序,也可以自定义实现compareTo()方法来指定元素排序规则,不能保证同优先级元素的顺序。
使用
使用较简单就不介绍了。
源码解析
- ReentrantLock+Condition原理
一个ReentrantLock一个Condition
private final ReentrantLock lock;
//取等待,存唤醒
private final Condition notEmpty;
- offer(E e)(add,put,offer一样)
如果容量已满,则返回false,添加失败;如果是第一次添加则会唤醒一个等待中的取数据;如果添加数据中,还有容量则会以传播的形式唤醒等待中的存数据
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;
}
- poll()
去优先级高的数据
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return dequeue();
} finally {
lock.unlock();
}
}
- take()
如果数据没有,则等待
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;
}
- poll(long timeout, TimeUnit unit)
如果数据没有,则等待timeout时长
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;
}