/*** The main timer loop. (See class comment.)*/privatevoidmainLoop() {while(true) {try{//to be scheduled taskTimerTask task;//fired one task?booleantaskFired;synchronized(queue) {//Wait for queue to become non-emptywhile(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 thinglongcurrentTime, executionTime;
task=queue.getMin();synchronized(task.lock) {if(task.state==TimerTask.CANCELLED) {//find the first task from the queue.queue.removeMin();continue;//No action required, poll queue again}//here ,use system current time to determin whether or not fire a taskcurrentTime=System.currentTimeMillis();
executionTime=task.nextExecutionTime;//So when we change system time to long ago,this expression will be evaluate to falseif(taskFired=(executionTime<=currentTime)) {if(task.period==0) {//Non-repeating, removequeue.removeMin();
task.state=TimerTask.EXECUTED;
}else{//Repeating task, reschedulequeue.rescheduleMin(
task.period<0?currentTime-task.period
: executionTime+task.period);
}
}
}if(!taskFired)//Task hasn't yet fired; waitqueue.wait(executionTime-currentTime);
}if(taskFired)//Task fired; run it, holding no lockstask.run();
}catch(InterruptedException e) {
}
}
}