使用 scheduledthreadpoolexecutor 的核心在于通过工厂方法创建实例,并调用 scheduleatfixedrate 或 schedulewithfixeddelay 提交周期性任务。你需要传入一个实现了 runnable 接口的对象、初始延迟时间以及周期间隔,线程池会自动在后台按指定频率执行该任务。如果任务执行时间超过周期,固定速率模式会等待当前任务完成后立即开始下一次,而固定延迟模式则会在任务结束后等待指定间隔再开始。

如何创建一个可执行周期性任务的线程池
要启动周期性任务,必须实例化 ScheduledThreadPoolExecutor 并设置核心线程数,通常设为 1 以避免多个线程竞争同一个任务。接着定义一个 Runnable 实现类,在其中编写具体的业务逻辑,例如打印日志或处理数据。最后调用 scheduleAtFixedRate 方法将任务提交给线程池,该方法会立即返回一个 ScheduledFuture 对象,用于后续取消任务。线程池会根据设定的核心线程数复用线程,确保任务持续运行直到被显式关闭或取消。

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class SchedulerDemo {
public static void main(String[] args) {
// 创建核心线程数为 1 的调度线程池
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
// 定义任务逻辑
Runnable task = () -> System.out.println("Task executed at " + System.currentTimeMillis());
// 提交周期性任务:初始延迟 0,间隔 1 秒
executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
// 保持主线程运行以便观察输出
try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }
// 关闭线程池
executor.shutdown();
}
}
上述代码创建了一个单线程的调度器,每秒钟执行一次打印操作。预期结果是控制台每隔一秒输出一行包含当前时间戳的信息。由于核心线程数为 1,即使任务执行时间稍长,也不会产生新的线程,而是串行执行。若需停止任务,可调用 ScheduledFuture.cancel(true) 或直接关闭整个线程池。
立即学习“Java免费学习笔记(深入)”;
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
scheduleAtFixedRate 与 scheduleWithFixedDelay 的区别是什么
这两种方法的主要区别在于周期的计算起点不同。scheduleAtFixedRate 以任务开始执行的时间为基准,无论任务耗时多久,下一次执行都在固定的时间点触发;如果任务执行时间超过周期,下一次执行会紧接着上一次任务结束后的瞬间发生。scheduleWithFixedDelay 则以任务结束时间为基准,每次任务结束后等待固定的延迟时间才开始下一次执行。这意味着如果任务耗时波动较大,固定延迟模式能保证两次任务之间至少有指定的空闲时间,而固定速率模式则可能因为任务堆积导致执行频率变慢。

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class DelayComparison {
public static void main(String[] args) {
ScheduledThreadPoolExecutor fixedRate = new ScheduledThreadPoolExecutor(1);
ScheduledThreadPoolExecutor fixedDelay = new ScheduledThreadPoolExecutor(1);
Runnable slowTask = () -> {
try { Thread.sleep(2000); } catch (InterruptedException e) {}
System.out.println("Task finished at " + System.currentTimeMillis());
};
// 固定速率:周期 1s,任务耗时 2s
fixedRate.scheduleAtFixedRate(slowTask, 0, 1, TimeUnit.SECONDS);
// 固定延迟:延迟 1s,任务耗时 2s
fixedDelay.scheduleWithFixedDelay(slowTask, 0, 1, TimeUnit.SECONDS);
try { Thread.sleep(10000); } catch (InterruptedException e) {}
fixedRate.shutdown();
fixedDelay.shutdown();
}
}
在上面的对比示例中,两个线程池都执行一个耗时 2 秒的任务。对于 scheduleAtFixedRate,由于周期仅为 1 秒,任务尚未完成时下一个周期已到达,因此线程池会等待当前任务结束后立即启动下一次,实际间隔接近 2 秒。而对于 scheduleWithFixedDelay,任务结束后会额外等待 1 秒才启动下一次,总间隔为 3 秒。这种差异在处理对时间精度要求不同的场景时至关重要,例如定时采集数据适合固定速率,而避免资源过载适合固定延迟。
当任务抛出未捕获异常时会发生什么
如果提交的 Runnable 任务在执行过程中抛出了未捕获的运行时异常,ScheduledThreadPoolExecutor 会终止该特定任务的后续执行,但不会关闭整个线程池。这意味着其他已提交的任务仍会继续正常运行,但该异常任务不会再被调度。线程池本身处于健康状态,可以继续接受新任务。这种行为类似于普通线程池中未捕获异常导致线程退出,但在调度上下文中,它表现为单个任务的静默失败。开发者应在任务内部使用 try-catch 块来捕获异常,以确保调度的连续性。
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ExceptionHandling {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Runnable faultyTask = () -> {
if (System.currentTimeMillis() % 2 == 0) {
throw new RuntimeException("Simulated error");
}
System.out.println("Normal execution");
};
executor.scheduleAtFixedRate(faultyTask, 0, 1, TimeUnit.SECONDS);
try { Thread.sleep(3000); } catch (InterruptedException e) {}
executor.shutdown();
}
}
运行此代码时,一旦 faultyTask 抛出异常,该任务的后续调度将停止,控制台不再输出“Normal execution”。然而,线程池并未崩溃,仍可提交其他正常任务。这要求在生产环境中,务必在任务逻辑外层包裹异常处理机制,防止因个别任务故障导致整个调度链断裂。

















