Timer 源码解读 (2) TaskQueue 最小堆实现的优先队列
2014-04-06 11:03
89 查看
Timer中的定义:
定义了一个队列:
Taskqueue是对一个队列的封装,这个队列实现的一个数据结构 a balanced binary heap 平衡二叉堆 并且根据TimerTask中的nextExecutionTime进行排序,最小值在堆顶
添加元素并排序:
获得最小元素并排序:
整体重排序:
fixUp和fixDown是堆排序方法:当插入元素,移除元素的时候都需要重新排序,以使得最小元素在堆顶
private final TaskQueue queue = new TaskQueue();
定义了一个队列:
class TaskQueue { /** * Priority queue represented as a balanced binary heap: the two children * of queue 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; } }
相关文章推荐
- go利用最小堆实现优先队列
- 最小堆实现优先队列解决修理牧场(c/c++)
- 最小堆优先队列C++实现
- 最小堆实现优先队列:Python实现
- 索引优先队列-IndexedPrirotyQueue的原理及实现(源码)
- 优先队列(堆)C++实现源码
- 常用类之三----最小堆实现优先队列
- min heap priority queue 最小堆实现的优先队列
- 最小堆实现优先队列:Python实现
- Spark 定制版:009~Spark Streaming源码解读之Receiver在Driver的精妙实现全生命周期彻底研究和思考
- POJ 3253 Fence Repair 题解(优先队列实现哈夫曼树)
- SpringMVC源码解读 - RequestMapping注解实现解读 - ConsumesRequestCondition
- Retrofit 源码解读之离线缓存策略的实现
- 每日一省————使用二叉堆实现优先队列
- 最小优先队列--堆实现
- 基于ZooKeeper实现队列源码
- java集合源码解读---Queu和Stack的数组和链式实现
- 学习记录2:优先队列 (二叉堆实现)
- Mangos源码分析(8):服务器公共组件实现之消息队列
- spring源码解读-InitializingBean的实现方法