Timer使用及工作原理

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进行消费。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值