结论
其实自己在看这个源码的时候,只是看到这两个方法都是周期性执行任务的,但是没有仔细去看两个方法的细节,所以,这篇笔记主要记录两者的区别
整个源码细节看下来之后,我认为这两个方法最大的一个区别是:
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