java.util.Timer调度浅析

来源:互联网 发布:中国知名的php培训机构 编辑:程序博客网 时间:2024/06/09 19:38

Timer是JDK中的定时调度类,主要用来定时触发任务:

  1. 用法:

Timer是调度控制器,TimerTask是可调度的任务:

package com.zemel.core;import java.util.Date;import java.util.TimerTask;public class PlainTimerTask extends TimerTask {@Overridepublic void run() {System.out.println(new Date());}}

调度过程:

package com.zemel.core;import java.util.Timer;public class TimerRunner {public static void main(String[] args) {Timer timer = new Timer();timer.schedule(new PlainTimerTask(), 5000L);}}

2.原理:

     其基本处理模型是单线程调度的任务队列模型,Timer不停地接受调度任务,所有任务接受Timer调度后加入TaskQueue,TimerThread不停地去TaskQueue中取任务来执行.




从图上不难看出,这就是生产者--消费者模型的一种特例:多生产者,单消费者模型。

     此种消息队列实现方式在浏览器中的编程模型中也有类似的实现,javascript中的定时执行函数setTimeout(expression,milliseconds)也是基于此种原理实现的。

     此种方式的不足之处为当某个任务执行时间较长,以致于超过了TaskQueue中下一个任务开始执行的时间,会影响整个任务执行的实时性。为了提高实时性,可以采用多个消费者一起消费来提高处理效率,避免此类问题的实现。

 

3.核心代码:


private void mainLoop() {    while (true) {        try {            TimerTask task;            boolean taskFired;            synchronized(queue) {                // Wait for queue to become non-empty                while (queue.isEmpty() && newTasksMayBeScheduled)                    queue.wait();                if (queue.isEmpty())                    break; // Queue is empty and will forever remain; die                // Queue nonempty; look at first evt and do the right thing                long currentTime, executionTime;                task = queue.getMin();                synchronized(task.lock) {                    if (task.state == TimerTask.CANCELLED) {                        queue.removeMin();                        continue;  // No action required, poll queue again                    }                    currentTime = System.currentTimeMillis();                    executionTime = task.nextExecutionTime;                    if (taskFired = (executionTime<=currentTime)) {                        if (task.period == 0) { // Non-repeating, remove                            queue.removeMin();                            task.state = TimerTask.EXECUTED;                        } else { // Repeating task, reschedule                            queue.rescheduleMin(                              task.period<0 ? currentTime   - task.period                                            : executionTime + task.period);                        }                    }                }                if (!taskFired) // Task hasn't yet fired; wait                    queue.wait(executionTime - currentTime);            }            if (taskFired)  // Task fired; run it, holding no locks                task.run();        } catch(InterruptedException e) {        }    }}

核心流程解释:

1.先获得队列锁,然后去TaskQueue中取TimerTask,然后去判断此队列为空且新任务可安排标记是打开的。如果不满足,线程等待,将队列锁释放。

2.如果队列为空,那么跳出死循环。

3.取得队列中的下一个元素,并获得任务锁。

4.检查任务状态,如果任务状态为取消,那么直接取消,并跳过此轮循环。

5.得到任务的计划执行时间,并检查与当前时间的先后,如果当前时间已经到或者超过计划执行时间,那么置状态位为执行。

6.释放任务锁。

7.如果没有,线程等待执行时间和当前时间差。

8.释放队列锁

9.看任务是否可以执行标记,来确定是否执行任务

10反复从1开始




0 0
原创粉丝点击