ScheduledExecutorService的scheduleAtFixedRate和scheduleWithFixedDelay的区别

分类: /

时间:

有时侯,自己只需要简单写代码就可以证实的东西,可以自己先实验下,避免部分不正确的言论误导自己

  1. import java.util.Date;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.ScheduledExecutorService;
  4. import java.util.concurrent.TimeUnit;
  5. public class Test {
  6. public static void main(String[] args) {
  7. ScheduledExecutorService executorServiceRate = Executors.newSingleThreadScheduledExecutor();
  8. ScheduledExecutorService executorServiceDelay = Executors.newScheduledThreadPool(2);
  9. executorServiceRate.scheduleAtFixedRate(new Task("fixed-rate"), 0, 1, TimeUnit.SECONDS);
  10. executorServiceDelay.scheduleWithFixedDelay(new Task("fixed-delay"), 0, 1, TimeUnit.SECONDS);
  11. }
  12. }
  13. class Task implements Runnable {
  14. private String name;
  15. public Task(String name) {
  16. this.name = name;
  17. }
  18. @Override
  19. public void run() {
  20. try {
  21. Thread.sleep(2000);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. System.out.println("name = " + name + ", now = " + new Date());
  26. }
  27. }

控制台输出

  1. name = fixed-rate, now = Wed Nov 29 18:48:06 CST 2017
  2. name = fixed-delay, now = Wed Nov 29 18:48:06 CST 2017
  3. name = fixed-rate, now = Wed Nov 29 18:48:08 CST 2017
  4. name = fixed-delay, now = Wed Nov 29 18:48:09 CST 2017
  5. name = fixed-rate, now = Wed Nov 29 18:48:10 CST 2017
  6. name = fixed-rate, now = Wed Nov 29 18:48:12 CST 2017
  7. name = fixed-delay, now = Wed Nov 29 18:48:12 CST 2017
  8. name = fixed-rate, now = Wed Nov 29 18:48:14 CST 2017
  9. name = fixed-delay, now = Wed Nov 29 18:48:15 CST 2017
  10. name = fixed-rate, now = Wed Nov 29 18:48:16 CST 2017
  11. name = fixed-delay, now = Wed Nov 29 18:48:18 CST 2017

总结

  • 无论是 scheduleAtFixedRate 还是 scheduleWithFixedDelay 都会是在上一次任务执行完才执行(及同一个时间点,不会有2个task都在运行)
  • 区别在于, FixedRate 执行完后,如果已经到了(超过)下一个的执行时间点的情况,会直接执行,而FixedDelay,会顺着当前的时间点延到下一个周期再开始执行

最后更新:2018-03-04 10:15:19.0

—— 原创内容,转载请注明:[ 文章转载自:小春 ' s blog   https://xiaochun.zrlog.com/ ] ——