ScheduledThreadPoolExecutor线程池

1. ScheduledThreadPoolExecutor线程池
2. SpringBoot2.X整合定时线程池(ScheduledThreadPoolExecutor)

image.png

1. 线程池的构造方法

ScheduledThreadPoolExecutor最全构造方法:

    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       ThreadFactory threadFactory,
                                       RejectedExecutionHandler handler) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue(), threadFactory, handler);
    }

我们自定义ScheduledThreadPoolExecutor线程池的时候,可以设置核心线程数、线程工厂、拒绝策略

阻塞队列默认使用的是DelayedWorkQueue(延迟队列,是一个优先级队列,本质上就是堆)。保证每次出队时一定是当前队列中执行时间最靠前的。

使用Executors静态类快速创建ScheduledThreadPoolExecutor:

 Executors.newScheduledThreadPool(3);

2. 添加延时任务

因为ScheduledThreadPoolExecutor实现了ExecutorService接口,那么他也能够使用通用的executor或者submit提交任务,最终调用schedule方法,默认马上执行一次。若需要延迟执行,可直接使用schedule方法,传递时间参数。

//延迟delay时间后,执行任务。因为传入的是Runnable,故get()方法获取的为null
public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);
 //带返回值的延迟任务
 public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit);

3. 添加周期任务

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);
  • scheduleAtFixedRate:按照固定的频率执行,不受执行时长影响,若发生misfire(即上一次执行时长大于period),则下一次任务立即执行。
  • scheduleWithFixedDelay:任务执行完毕后,按照固定的delay时间间隔执行。

4. 如何终止周期任务

方式一:抛出异常,即可终止定时任务。

        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
        scheduledExecutorService.scheduleWithFixedDelay(() -> {
            System.out.println("start scheduled...");
            throw new RuntimeException();
        }, 0, 1000, TimeUnit.MILLISECONDS);

方式二:调用Future的cancal方法

future.cancel(false);

文章参考

线程池之ScheduledThreadPoolExecutor

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容