定时线程池:ScheduledThreadPoolExecutor

什么是ScheduledThreadPoolExecutor?

ScheduledThreadPoolExecutorJUC中用于定时任务调用周期性任务执行 的核心类。它继承于ThreadPoolExecutor,与普通线程池不同的是,它使用的BlockingQueueDelayedWorkQueue,这使得它能够按照时间顺序调度任务。

ScheduledThreadPoolExecutor内部原理

ScheduledFutureTask

ScheduledThreadPoolExecutor 将任务封装成 ScheduledFutureTask,然后放入一个特殊的阻塞队列 DelayedWorkQueue

ScheduledFutureTask是具有返回值的任务, 继承自FutureTaskFutureTask的内部有 一个变量state用来表示任务的状态, 一开始状态为NEW, 所有状态为

java 复制代码
private static final int NEW          = 0; // 初始状态,任务尚未开始或尚未完成
private static final int COMPLETING   = 1; // 正在完成,结果已设置但尚未通知等待线程
private static final int NORMAL       = 2; // 正常完成,任务执行成功并设置了结果
private static final int EXCEPTIONAL  = 3; // 异常完成,任务执行过程中抛出了异常
private static final int CANCELLED    = 4; // 已取消,任务在完成前被取消(未响应中断)
private static final int INTERRUPTING = 5; // 正在中断,任务已被中断但中断操作尚未完成
private static final int INTERRUPTED  = 6; // 已中断,任务已被中断且中断操作已完成

并且ScheduledFutureTask内部还有一个变量period用来表示任务的类型:

  • period == 0:一次性任务(非周期性)。
  • period > 0scheduleAtFixedRate,固定频率。
  • period < 0scheduleWithFixedDelay,固定延迟。

ScheduledThreadPoolExecutor方法

构造方法

java 复制代码
public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}

其中DelayedWorkQueue是一个无界队列,因此maximumPoolSize=Integer.MAX_VALUE这个参数没有意义。

重要方法

ScheduledThreadPoolExecutor有三个重要的函数

  1. schedule(Runnable/Callable, delay, TimeUnit)
  • 在指定的 delay 时间后,执行一次任务。
  • 返回 ScheduledFuture,可用于取消任务或获取结果。
  1. scheduleAtFixedRate(Runnable, initialDelay, period, TimeUnit)
  • initialDelay 后开始第一次执行,然后每隔 period 时间执行一次。
  • 这里的 period 是指两次任务开始执行的时间间隔
  • 如果某次任务执行时间超过了 period,下一次执行会立即开始,不会并发执行同一个任务(同一个任务实例不会同时运行两次)。
  • 适合"固定频率"的场景,如每5秒采集一次状态。
  1. scheduleWithFixedDelay(Runnable, initialDelay, delay, TimeUnit)
  • initialDelay 后开始第一次执行,之后在上一次执行完成后,等待 delay 时间再执行下一次
  • delay 是指前一次执行结束到下一次执行开始的间隔
  • 适合"固定间隔等待"的场景,如发送完一条消息后等 10 秒再发下一条。
相关推荐
程序员黑豆28 分钟前
Java中怎么实现字符串拼接呢【AI全栈开发】
java
fox_lht1 小时前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
大鸡腿同学1 小时前
用 AI 肝了一个星期的智能客服助手,看看怎么个事
后端
IT_陈寒1 小时前
Python的os.path.join居然能这么坑?
前端·人工智能·后端
java1234_小锋1 小时前
LangChain4j 开发Java Agent智能体- 多模态支持
java·开发语言·langchain4j
艳阳天_.1 小时前
星瀚弹框页面实现
java·前端·python
张忠琳1 小时前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
Rain5092 小时前
2.1 Nest.js 项目初始化与模块化架构
开发语言·前端·javascript·后端·架构·数据分析·node.js
cjp5602 小时前
009. ASP.NET WEB API 用户关联esp32设备
前端·后端·asp.net