守护线程如何退出?Timer源码所得

本文深入探讨了Java中Timer类的工作原理及其内部实现机制,重点分析了Timer类中的关键变量及线程退出机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

近日要做定时任务,看了看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掉,否则等到垃圾回收线程才能退出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值