参照博文地址:https://www.jianshu.com/p/def7f016dd5e https://www.cnblogs.com/luckygxf/p/7078662.html https://blog.csdn.net/chinese_zhang/article/details/51566693
总结:
Timer 类中有TaskQueue,他里面有个TimerTask数组queue,类中方法主要操作queue数组(添加任务,删除queue数组任务,查询queue等等)。
TimerThread,他继承Thread,当new Timer()时,Timer构造器中启动了TimerThread线程,执行TimerThread的mainLoop方法,这个方法是whie(true)循环,它是Timer定时中最重要的一个。
TimerTask: 它实现了Runnable接口,有执行时间nextExecutionTime字段,period间隔时间,和他的状态(是否为定时任务,任务是否被执行了,任务是否清除了)。
mainLoop()方法:
1 private void mainLoop() { 2 while (true) { 3 try { 4 TimerTask task; 5 boolean taskFired; 6 synchronized(queue) { 7 // Wait for queue to become non-empty 8 while (queue.isEmpty() && newTasksMayBeScheduled) //当new Timer时,他未添加TimerTask任务且newTasksMayBeScheduled为true是,wait(),当添加任务是在notify() 9 queue.wait(); 10 if (queue.isEmpty()) 11 break; // Queue is empty and will forever remain; die 12 13 // Queue nonempty; look at first evt and do the right thing 14 long currentTime, executionTime; 15 task = queue.getMin(); //获取queue[1]任务,queue[0] 解释:The head task is antask with the lowest nextExecutionTime 16 synchronized(task.lock) { 17 if (task.state == TimerTask.CANCELLED) { //任务已经移除的 18 queue.removeMin(); 19 continue; // No action required, poll queue again 20 } 21 currentTime = System.currentTimeMillis(); 22 executionTime = task.nextExecutionTime; //获取本次任务执行时间 23 if (taskFired = (executionTime<=currentTime)) { 24 if (task.period == 0) { // Non-repeating, remove //间隔时间 25 queue.removeMin(); 26 task.state = TimerTask.EXECUTED; 27 } else { // Repeating task, reschedule 28 queue.rescheduleMin( 29 task.period<0 ? currentTime - task.period 30 : executionTime + task.period); 31 } 32 } 33 } 34 if (!taskFired) // Task hasn't yet fired; wait 35 queue.wait(executionTime - currentTime); 36 } 37 if (taskFired) // Task fired; run it, holding no locks 38 task.run(); 39 } catch(InterruptedException e) { 40 } 41 } 42 }