小顶堆
PriorityQueue\DelayedWorkQueue\PriorityBlockingQueue
小顶堆的实现,主要用于快速输出最小值,时间、空间复杂度都很低,不存在平衡
性。相比于借助二分查找法完成有序列表,每次输出数组首位,后面再整体移位,这种做法,维护有序性的时间成本高!
Java堆结构PriorityQueue完全解析
PriorityQueue
有两个应用场景 1、优先级队列 2、延时执行ScheduledThreadPoolExecutor。
延时执行的实现方式是:当前时间点+延时时长 作为 K , 线程池到任务队列中取任务时,若时间未到则发生阻塞,阻塞时长available.awaitNanos(delay); 具体代码如下:
public RunnableScheduledFuture<?> take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
for (;;) {
RunnableScheduledFuture<?> first = queue[0];
if (first == null)
available.await();
else {
long delay = first.getDelay(NANOSECONDS);
if (delay <= 0)
return finishPoll(first);
first = null; // don't retain ref while waiting
if (leader != null)
available.await();
else {
Thread thisThread = Thread.currentThread();
leader = thisThread;
try {
available.awaitNanos(delay);
} finally {
if (leader == thisThread)
leader = null;
}
}
}
}
} finally {
if (leader == null && queue[0] != null)
available.signal();
lock.unlock();
}
}
二叉查找树
二叉树的遍历,用中序遍历的结果是,从小到大排序。
/**
* 中序遍历,
* 每个叶子节点可以看做是,左右子叶子节点都为null的父节点
*/
public void midForeach(int index) {
if (isV(index)) {
return;
}
midForeach(index * 2);
System.out.print(array[index] + ",");
midForeach(index * 2 + 1);
}
网友评论