主要邏輯: 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) {
}
}
}