ScheduledThreadPoolExecutor之scheduleWithFixedDelay和scheduleAtFixedRate的区别

结论

其实自己在看这个源码的时候,只是看到这两个方法都是周期性执行任务的,但是没有仔细去看两个方法的细节,所以,这篇笔记主要记录两者的区别
整个源码细节看下来之后,我认为这两个方法最大的一个区别是:
scheduleAtFixedRate是在上一次任务的开始时间的基础之上,加上指定的时间间隔,作为当前任务执行的开始时间
scheduleWithFixedDelay是在上一次任务执行完毕之后的基础之上,加上指定的时间间隔,作为当前任务执行的开始时间

在这里插入图片描述
我们假如定时执行周期都设置为5S,任务执行需要耗时2S,以这个窗口作为执行时间刻度的话,区别就是上面图中所画的这样

应用

这个代码的意思是:初始化了一个ScheduledThreadPoolExecutor,然后执行执行间隔是5S,每个任务中休眠了2S,模拟需要耗时2S的操作

scheduleAtFixedRate
public class ScheduledThreadPoolTest {
   
    public static void main(String[] args) {
   
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(4);
        SimpleDateFormat sm = new SimpleDateFormat("hh:MM:ss");
        System.out.println("当前时间是:"+sm.format(new Date()));
        scheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() {
   
            @Override
            public void run() {
   
                try {
   
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
                System.out.println("这是执行的内容:" + sm.format(new Date()));
            }
        }, 5, 5, TimeUnit.SECONDS);
    }
}

打印结果:

当前时间是:08:03
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值