读书人

java.util.Timer 中schedule跟schedu

发布时间: 2012-12-19 14:13:14 作者: rapoo

java.util.Timer 中schedule和scheduleAtFixedRate的区别

最近项目中大量用到Timer 总结一下.

schedule安排指定的任务在指定的时间开始进行重复的固定延迟执行

scheduleAtFixedRate安排指定的任务从指定的延迟后开始进行重复的固定延迟执行

参考http://blog.csdn.net/gtuu0123/archive/2010/11/27/6040159.aspx 对schedule和scheduleAtFixedRate的分析.

但它仅仅分析了部分,查看JDK的源代码java.util.Timer分析以下几段:

 /**     * The main timer loop.  (See class comment.)     */    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) {            }        }    }

?以while(true)方式来调用task.run()方法.由此分析TimerTask中的run方法不存在同步的问题,如果执行时间超出设置时间,会直接再次执行run()而没有时间间隔!!!!

读书人网 >编程

热点推荐