TimerThread

Timer源码之TimerThread

橙三吉。 提交于 2020-01-07 12:38:35
【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>> Timer只是管理着一个TimerTask任务队列(queue)而TimerTask的真正执行是由TimerThread来执行的,TimerThread继承了Thread,它的主要工作就是不断从优先级队列queue中取出任务检查是否到了可以执行的时间,如果可以执行就调用TimerTask的run方法。 非常值得注意的是任务队列(queue)中的TimerTask虽然实现了Runnable接口,但是在TimerThread中并没有启动新的线程来执行它,只有Thread的start方法才能启动新的线程。所以如果TimerTask中的run方法是死循环,那么可能Timer的任务队列中的TimerTask永远得不到执行的机会。还是先看一下TimerThread的代码吧。 import java.util.TimerTask; public class TimerThread extends Thread { boolean newTasksMayBeScheduled = true; /** * 任务队列的引用 */ private TaskQueue queue; TimerThread(TaskQueue queue) { this.queue = queue; } public void run() { try