并发-ScheduledThreadPoolExecutor

参考:

https://blog.csdn.net/qq_36299025/article/details/89491384

todo

https://blog.csdn.net/luanmousheng/article/details/77816412

https://www.cnblogs.com/200911/p/6042417.html

http://ifeve.com/33981-2/ 

线程池之ScheduledThreadPool学习

简介

ScheduledThreadPool是一个能实现定时、周期性任务的线程池。

创建方法

 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }


这里创建了ScheduledThreadPoolExecutor,ScheduledThreadPoolExecutor继承自ThreadPoolExecutor,主要用于给定 延时之后的运行任务或定期处理任务。ScheduledThreadPoolExecutor的构造方法如下:

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

ScheduledThreadPoolExecutor构造方法中最终调用的是父类ThreadPoolExecutor的构造方法;corePoolSize是传递进来的固定数值,maximumPoolSize的值是Integer.MAX_VALUE;DelayedWorkQueue是无界的,因此maximumPoolSize是无效的。

execute方法执行

在这里插入图片描述当执行ScheduledThreadPoolExecutor的scheduleAtFixedRate或scheduleWithFixedDelay方法,会向DelayedWorkQueue添加一个实现RunnableScheduledFuture接口的任务包装类ScheduledFutureTask,并检查运行的线程是否达到核心线程数corePoolSize。
如果没有就新建线程,并启动。但并非立即执行任务,而是去DelayedWorkQueue中取任务包装类ScheduledFutureTask,然后再去执行任务;
如果运行的线程达到了corePoolSize,就把任务添加到任务队列DelayedWorkQueue中;DelayedWorkQueue会将任务排序,先执行的任务放在队列的前面。
任务执行完后,ScheduledFutureTask中的变量time改为下次要执行的时间,并放回到DelayedWorkQueue中。

原文地址:https://www.cnblogs.com/xuwc/p/14053654.html