主要逻辑: new 一个 Timer 后, timer 内部维护一个队列 queue,并开启一个死循环线程 从
queue 中取任务执行( 触发时间到了就执行,未到就 wait ),timer.schedule( TimerTask ) 其实就是 将 任务体放入队列中 ( ps: timer 运行多个 TimerTask 时只要一个没有捕获抛出的异常异常,则此 timer 便停止了,所以建议使用 ScheduledExecutorService 代替 Timer )
private void mainLoop() {
while (true) {
try {
TimerTask task;
boolean taskFired;
synchronized(queue) {
// Wait for queue to become non-empty
while (queue.isEmpty() && newTasksMayBeScheduled){
// 任务队列中没有待调度的任务,just wait!
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
// 触发时间还没到, 延迟 wait
queue.wait(executionTime - currentTime);
}
}
if (taskFired){ // Task fired; run it, holding no locks
// 触发时间到了,执行任务体( 这里的 task 即是 实现了 Runnable 接口的 TimerTask 任务体 )
task.run();
}
} catch(InterruptedException e) {
}
}
}