ScheduledExecutorService与Timer的方法比较

本文详细比较了ScheduledExecutorService与Timer中scheduleAtFixedRate方法的工作原理,包括它们如何在指定延迟后首次执行任务,以及如何按固定周期重复执行。此外,还介绍了ScheduledExecutorService特有的scheduleWithFixedDelay方法及其执行机制。

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

ScheduledExecutorService与Timer都有scheduleAtFixedRate方法

一、相同名称的方法

scheduleAtFixedRate

ScheduledExecutorService 的 scheduleAtFixedRate(Runnable command,long initialDelay,long period1,TimeUnit unit) 与Timer 的 scheduleAtFixedRate(TimerTask task, long delay, long period2) 功能是一样的:

initialDelay/delay后第一次执行command/task

然后在第一次开始执行command/task的时间点开始算,period1/period2后第二次执行command/task

然后在第二次开始执行command/task的时间点开始算,period1/period2后第三次执行command/task

然后在第三次开始执行command/task的时间点开始算,period1/period2后第四次执行command/task

...

...

...

如果delay/period后的时间点上一次的command/task还没有执行完,那么会等到上一次的执行完,才会开始下一次的执行。


二、ScheduledExecutorService的方法

scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit)功能为:

initialDelay后第一次执行command

然后在第一次结束执行command的时间点开始算delay后第二次执行command;

然后在第二次结束执行command的时间点开始算,delay后第三次执行command;

然后在第三次结束执行command的时间点开始算,delay后第四次执行command;

...

...

...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值