源码:java.util.concurrent.ScheduledExecutorService 源码解析

1. TODO


2. 脑图

  1. Xmind

  2. Edraw

  3. Hexo 地址
    👉 http://blog.wangjia.ink/2025/11/03/源码:java.util.concurrent.ScheduledExecutorService源码解析/


3. 基础部分

3.1. ScheduledExecutorService 概述

ScheduledExecutorService 是一个接口,继承了 java.util.concurrent.ExecutorService

ScheduledExecutorServiceExecutorService 的基础上,为我们提供了以下方法:

  1. 提交一个 Runnable 任务并延迟执行(非阻塞)
  2. 提交一个 Runnable 任务并以固定速率周期性执行(非阻塞)
  3. 提交一个 Runnable 任务并以固定延迟周期性执行(非阻塞)
  4. 提交一个 Callable 任务并延迟执行(非阻塞)

简单来说,ExecutorService 提供的方法都是任务提交后 “立即执行”,但是 ScheduledExecutorService 允许我们延迟执行任务、周期性执行任务

[!NOTE] 注意事项

  1. 详见源码:ExecutorService
    1. obsidian 内部链接:
      1. 源码:java.util.concurrent.ExecutorService源码解析
    2. Hexo 链接:
      1. http://blog.wangjia.ink/2025/09/03/源码:java.util.concurrent.ExecutorService源码解析/
  2. 所谓的 “延迟执行” 是指:在指定的延迟时间到达后,任务 “可以被执行”。但它是否会立即真正运行,还取决于是否有空闲线程可以执行该任务。因此在高并发场景下,任务的实际执行时间可能会比指定的延迟时间更晚。

4. 源码部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public interface ScheduledExecutorService extends ExecutorService {

// 用于非阻塞提交一个 Runnable 任务,并延迟 delay unit 时间后再执行
public ScheduledFuture<?> schedule(Runnable comm
long delay, TimeUnit unit);

// 用于非阻塞提交一个 Callable 任务,并延迟 delay unit 时间后再执行
public <V> ScheduledFuture<V> schedule(Callable<V> callable,
long delay, TimeUnit unit);

// 用于非阻塞提交一个 Runnable 任务,并延迟 delay unit 时间后再执行,并以固定速率周期性执行
//
// 延迟 initialDelay unit 时间后首次执行
//
// 然后以 period unit 固定速率周期性执行,例如 initialDelay unit 为 0s,period unit 为 5s
// 1. 第一次执行开始的时间为 0s
// 2. 第二次执行快速的时间为 5s
// 3. 第三次执行开始的时间为 10s
// 4. 以此类推...
// 5. 如果第一次执行的任务,耗时 7s,则该任务执行完成后,需要再次立即执行,去弥补第二次的空缺
// 6. 如果第二次执行的任务,仍然耗时 7s,则该任务执行完成后,需要再次立即执行,去弥补第三次的空缺
// 7. 如果第三次执行的任务,依旧耗时 7s,则该任务执行完成后,需要再次立即执行,去弥补第四次的空缺
// 8. 以此类推...
//
// 需要注意的是,如果执行任务的耗时 > period unit,后续的任务执行可能会开始比较晚,但是不会并发执行。这种情况下就成一种连续执行了,上一个任务刚结束,下一个任务就开始,中间没有任何停顿
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);

// 用于非阻塞提交一个 Runnable 任务,并延迟 delay unit 时间后再执行,并以固定延迟周期性执行
//
// 延迟 initialDelay unit 后首次执行
//
// 然后以 period unit 固定延迟周期性执行,例如 initialDelay unit 为 0s,period unit 为 5s
// 1. 第一次执行的时间为 0s,如果该任务耗时 7s
// 2. 第二次执行的时间为 7s + 5s,即 12s,如果该任务耗时 5s
// 3. 第三次执行的时间为 12s + 5s,即 17s
// 4. 以此类推...
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);

}


源码:java.util.concurrent.ScheduledExecutorService 源码解析
https://wangjia5289.github.io/2025/11/03/源码:java.util.concurrent.ScheduledExecutorService源码解析/
Author
咸阳猴🐒
Posted on
November 3, 2025
Licensed under