ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor 是 Java 提供的一个线程池实现类,专门用于调度任务的执行,包括延迟执行任务和周期性执行任务。它继承自 ThreadPoolExecutor 并实现了 ScheduledExecutorService 接口。

1. ScheduledThreadPoolExecutor 基本概念

ScheduledThreadPoolExecutor 允许我们在特定的时间或周期内执行任务,适用于需要定时任务调度的场景,如定时任务、心跳检查等。

2. 构造方法

ScheduledThreadPoolExecutor 的常用构造方法:

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());
}
  • corePoolSize:核心线程数,即始终保持在线的线程数量。

3. 常用方法

  • schedule(Runnable command, long delay, TimeUnit unit):在指定延迟后执行一次任务。
  • schedule(Callable callable, long delay, TimeUnit unit):在指定延迟后执行一次任务,并返回结果。
  • scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit):以固定频率周期性地执行任务。
  • scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit):以固定延迟周期性地执行任务。

4. 使用示例

下面是一个使用 ScheduledThreadPoolExecutor 执行不同类型调度任务的示例:

import java.util.concurrent.*;

public class ScheduledThreadPoolExecutorDemo {
    public static void main(String[] args) {
        ScheduledThreadPoolExecutor scheduledExecutor = new ScheduledThreadPoolExecutor(2);

        // 延迟任务
        scheduledExecutor.schedule(() -> {
            System.out.println("Task executed after 3 seconds delay.");
        }, 3, TimeUnit.SECONDS);

        // 固定频率任务
        scheduledExecutor.scheduleAtFixedRate(() -> {
            System.out.println("Task executed at fixed rate.");
        }, 1, 5, TimeUnit.SECONDS);

        // 固定延迟任务
        scheduledExecutor.scheduleWithFixedDelay(() -> {
            System.out.println("Task executed with fixed delay.");
        }, 1, 5, TimeUnit.SECONDS);

        // 程序运行一段时间后关闭线程池
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        scheduledExecutor.shutdown();
    }
}

5. 详细解释

1. 延迟任务
scheduledExecutor.schedule(() -> {
    System.out.println("Task executed after 3 seconds delay.");
}, 3, TimeUnit.SECONDS);

这个方法会在延迟3秒后执行一次任务。

2. 固定频率任务
scheduledExecutor.scheduleAtFixedRate(() -> {
    System.out.println("Task executed at fixed rate.");
}, 1, 5, TimeUnit.SECONDS);

这个方法会在初始延迟1秒后,以固定的频率每5秒执行一次任务。如果任务执行时间超过了周期时间,那么任务会尽可能快地重新开始。

3. 固定延迟任务
scheduledExecutor.scheduleWithFixedDelay(() -> {
    System.out.println("Task executed with fixed delay.");
}, 1, 5, TimeUnit.SECONDS);

这个方法会在初始延迟1秒后,以固定的延迟每5秒执行一次任务。新的任务不会在之前任务完成之前启动,即每次任务执行完后再等待5秒再执行下一个任务。

6. 管理任务和线程池

如同 ThreadPoolExecutor,可以通过 shutdownshutdownNowisShutdownisTerminatedawaitTermination 等方法管理 ScheduledThreadPoolExecutor 的生命周期。

scheduledExecutor.shutdown();
try {
    if (!scheduledExecutor.awaitTermination(60, TimeUnit.SECONDS)) {
        scheduledExecutor.shutdownNow();
    }
} catch (InterruptedException e) {
    scheduledExecutor.shutdownNow();
    Thread.currentThread().interrupt();
}

总结

ScheduledThreadPoolExecutor 提供了强大的调度功能,可以方便地实现延迟任务和周期性任务。通过合理配置和管理,可以实现复杂的任务调度需求,提升应用程序的响应和性能。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值