• ScheduledThreadPoolExecutor详解与总结


    ScheduledThreadPoolExecutor详解简介

    • 继承自ThreadPooExecutor,为任务提供延迟或周期执行.
    • 使用专门的ScheduledFutureTask来执行周期任务,也可以接收不需要时间调度的任务.
    • 使用DelayedWorkQueue存储任务.(一种无界延迟队列)
    • 支持线程池关闭后可执行,可选择线程池关闭后支持继续执行周期或延迟任务.
    public class ScheduledThreadPoolExecutor 
    extends ThreadPoolExecutor implements 
    ScheduledExecutorService {}

    在源码中可以看到,ScheduledThreadPoolExecutor 的状态管理、入队操作、拒绝操作等都是继承于 ThreadPoolExecutor;ScheduledThreadPoolExecutor 主要是提供了周期任务和延迟任务相关的操作;

    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) // 固定延迟周期任务

    ScheduledThreadPoolExecutor的运行逻辑而言,大致可以表述为:

    首先将 Runnable/Callable 封装为 ScheduledFutureTask,延迟时间作为比较属性;
    然后加入DelayedWorkQueue 队列中,每次取出队首延迟最小的任务,超时等待,然后执行;
    最后判断是否为周期任务,然后重新加入DelayedWorkQueue 队列中;

    其内部结构如图所示:

    这里需要注意的:

    ScheduledThreadPoolExecutor 中的队列不能指定,只能是 DelayedWorkQueue;因为他是 无界队列,所以再添加任务的时候线程最多可以增加到 coreSize,这里不清楚的可以查看 ThreadPoolExecutor 详解,就不再重复了;
    ScheduledThreadPoolExecutor 重写了 ThreadPoolExecutor 的execute() 方法,其执行的核心方法变成 delayedExecute();
    
    

    参考博客:

    https://blog.csdn.net/cristianoxm/article/details/107640772
    https://www.jianshu.com/p/7018d21e4979
    https://blog.csdn.net/weixin_43942106/article/details/112261645

  • 相关阅读:
    八十五:redis之redis的事物、发布和订阅操作 (2019-11-18 22:54)
    八十四:redis之redis的集合、哈希操作
    八十三:redis之redis的字符串、过期时间、列表操作
    八十三:redis之redis的使用场景和安装
    八十二:memcached之python操作memcached
    八十一:memcached之telnet操作memcached
    八十:memcached之安装与参数
    MySQL篇之Navicat可视化工具
    MySQL数据库篇之多表查询
    MySQL数据库篇之单表查询
  • 原文地址:https://www.cnblogs.com/jelly12345/p/16628088.html
Copyright © 2020-2023  润新知