近日要做定时任务,看了看java.util.Timer源码,Timer类中有以下三个变量:
private TaskQueue queue = new TaskQueue();
/**
* The timer thread.
*/
private TimerThread thread = new TimerThread(queue);
/**
* This object causes the timer's task execution thread to exit
* gracefully when there are no live references to the Timer object and no
* tasks in the timer queue. It is used in preference to a finalizer on
* Timer as such a finalizer would be susceptible to a subclass's
* finalizer forgetting to call it.
*/
private Object threadReaper = new Object() {
protected void finalize() throws Throwable {
synchronized(queue) {
thread.newTasksMayBeScheduled = false;
queue.notify(); // In case queue is empty.
}
}
};
其中thread变量在timer初始化后开始启动,其start就是一个while(true)循环,不断取得queue中任务进行判断。。那么thread线程退出就是个问题了,当然Timer提供了cancel方法。
当quene变为了空,而这个timer类没有再被引用,那么如果不执行cancel则这个线程一直运行状态。当垃圾回收的时候,while(true)一直运行,所以不会退出。因此当timer进行回收时候,threadReaper 对象回收了,其finalize方法将queue清空,标识变量false,这样while循环中的判断break条件为真,退出循环,函数执行完毕了,线程也会退出了。
如果timer类不使用了,一定要cancel掉,否则等到垃圾回收线程才能退出。