`
how_it_works
  • 浏览: 5690 次
社区版块
存档分类
最新评论

Timer使用及工作原理

    博客分类:
  • jdk
阅读更多

Timer使用及工作原理


本文将结合源码来分析JDK timer的使用方法及工作原理。 以下源码均基于JDK1.6_14

JDK1.3加入Timer。


一、Timer的使用

 

		
//new task and schedule task (delay 2s exec)
                Timer timer = new Timer();	
		//add task1
		Task task = new Task("t1");
		timer.schedule(task,2000); 

 

Timer 使用很简单,schedule可以支持任务的延迟执行、周期执行、一次性执行。


 

二、Timer的原理

Timer中有三个非常重要的概念。一个就是 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 的实现非常简单,如上它的核心就是一个 Task数组,值得注意的是,每当Timer向TaskQueue添加一个任务的时候,它会根据任务的下次执行时间进行正序,保持最近一次要执行的任务总是在队列的最前面。

 

 

 

Timer的另外一个重要成员就是 TimerThread

 

class TimerThread extends Thread {
... ...

 TimerThread是 TaskQueue的consumer,而且每个Timer只有一个TimerThread的实例,也就是一个timer执行多个任务的时候,他是起一个TimerThread线程顺序执行队列中的任务。

 

 

与Timer息息相关的另外一个重要概念就是TImerTask

 

public abstract class TimerTask implements Runnable {

这个类很简单,除了 implements Runnable,类中还包含了一些Task的meta信息,如锁、状态、执行时间等。

 

 

三 总结

Timer类有一个TaskQueue,一个TimerThread对队列中的TimerTask进行消费。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics