Timer 源码解读 (2) TaskQueue 最小堆实现的优先队列
来源:互联网 发布:网络教育本科统考免考 编辑:程序博客网 时间:2024/05/22 05:26
Timer中的定义:
private final TaskQueue queue = new TaskQueue();
定义了一个队列:
class TaskQueue { /** * Priority queue represented as a balanced binary heap: the two children * of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is * ordered on the nextExecutionTime field: The TimerTask with the lowest * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For * each node n in the heap, and each descendant of n, d, * n.nextExecutionTime <= d.nextExecutionTime. */ private TimerTask[] queue = new TimerTask[128];
Taskqueue是对一个队列的封装,这个队列实现的一个数据结构 a balanced binary heap 平衡二叉堆 并且根据TimerTask中的nextExecutionTime进行排序,最小值在堆顶
添加元素并排序:
void add(TimerTask task) { // Grow backing store if necessary if (size + 1 == queue.length) queue = Arrays.copyOf(queue, 2*queue.length); queue[++size] = task; fixUp(size); }
获得最小元素并排序:
void removeMin() { queue[1] = queue[size]; queue[size--] = null; // Drop extra reference to prevent memory leak fixDown(1); }
整体重排序:
void heapify() { for (int i = size/2; i >= 1; i--) fixDown(i); }
fixUp和fixDown是堆排序方法:当插入元素,移除元素的时候都需要重新排序,以使得最小元素在堆顶
private void fixUp(int k) { while (k > 1) { int j = k >> 1; if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime) break; TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } }
private void fixDown(int k) { int j; while ((j = k << 1) <= size && j > 0) { if (j < size && queue[j].nextExecutionTime > queue[j+1].nextExecutionTime) j++; // j indexes smallest kid if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime) break; TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } }
0 0
- Timer 源码解读 (2) TaskQueue 最小堆实现的优先队列
- 最小优先队列--堆实现
- min heap priority queue 最小堆实现的优先队列
- c语言最小堆的实现-优先队列
- 最小堆优先队列C++实现
- 用最小堆实现优先队列
- 简单优先队列实现-基于最小堆
- 最小堆及基于最小堆的最小优先队列
- 最小堆得实现;优先队列的堆实现;堆排序的时间复杂度nlgn;
- java.util.TaskQueue的最小堆排序算法的应用
- 优先队列(堆)C++实现源码
- 数据结构实现之最小优先队列(最小堆)
- 堆的实现、堆排序、优先队列
- 优先队列(最小堆)
- 最小堆模拟优先队列
- 堆的优先队列2
- 优先队列实现堆
- 优先队列(堆实现)
- linux下vmstat命令解析 (性能相关以及系统性能诊断)
- UML类图各种关系详解
- Android API Guides 之 App Resources(3) - Accessing Resources
- 【Redis】初探dict字典原理的实现(二)
- 奇异值分解SVD应用——LSI
- Timer 源码解读 (2) TaskQueue 最小堆实现的优先队列
- (转)Linux网络编程之sockaddr与sockaddr_in,sockaddr_un结构体详细讲解
- Android API Guides 之 App Resources(4) - Handling Runtime Changes
- C++高精度运算模板
- 黑马从程序员_学习笔记 如何修改datatable的列名?
- 腾讯前端实习生面试经历
- Android API Guides 之 App Resources(5) - Localizing with Resources
- 最长不重叠字串
- LeetCode Linked List Cycle