使用ScheduledThreadPoolExecutor 替代 Timer

Java1.5引入的ScheduledThreadPoolExecutor在多数情况下优于Timer,因为Timer只有一个执行线程,可能导致任务堆积。当TimerTask抛出异常时,所有任务都会停止。此外,ScheduledExecutorService不受系统时间更改影响,更稳定。建议使用ScheduledExecutorService进行定时任务管理。

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

Java1.5之后提供了新的APIScheduledThreadPoolExecutor,这个组件大部分场景下是可以取代Timer的。
 
优点有三:
 
1  Timer管理延时任务的缺陷

    Timer是存在一些缺陷的,因为Timer在执行定时任务时只会创建一个线程,所以如果存在多个任务,且任务时间过长,超过了两个任务的间隔时间,会发生一些缺陷:下面看例子:

Timer的源码:
   
public class Timer {  
    /** 
     * The timer task queue.  This data structure is shared with the timer 
     * thread.  The timer produces tasks, via its various schedule calls, 
     * and the timer thread consumes, executing timer tasks as appropriate, 
     * and removing them from the queue when they're obsolete. 
     */  
    private TaskQueue queue = new TaskQueue();  
  
    /** 
     * The timer thread. 
     */  
    private TimerThread thread = new TimerThread(queue);  
 
 
2、Timer当任务抛出异常时的缺陷

如果TimerTask抛出RuntimeException,Timer会停止所有任务的运行.
 
 
3、Timer执行周期任务时依赖系统时间Timer执行周期任务时依赖系统时间,如果当前系统时间发生变化会出现一些执行上的变化,ScheduledExecutorService基于时间的延迟,不会由于系统时间的改变发生执行变化。



上述,基本说明了在以后的开发中尽可能使用ScheduledExecutorService(JDK1.5以后)替代Timer。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值