线程池(三)–ScheduledThreadPoolExecutor

  • Post author:
  • Post category:其他




什么是ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor是一个定时线程池,他是继承ThreadPoolExecutor类,所不同的是它具有定时执行,以周期或间隔循环执行任务等功能。

在这里插入图片描述



构造方法

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

从构造函数可以看出他继承了父类的属性,他的最大线程数为Integer.MAX_VALUE,且采用DelayQueue存储等待线程,DelayQueue是一个无界队列,内部封装了一个prioityQueue,它会根据time的先后时间排序,若time相同则根据sequenceNumber排序;



提交任务API

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

initialDelay:延迟第一次执行的时间

period:连续执行之间的时间间隔

delay:一个执行的终止和下一个执行的开始之间的延迟

首先是schedule方法,该方法是指任务在指定延迟时间到达后触发,只会执行一次。

scheduleAtFixedRate和scheduleWithFixedDelay从构造参数可以看出前者的执行时间差别,比如我第一个线程从0开始执行,执行需要5s,延时2s,用scheduleAtFixedRate方法则从第2s开始就准备执行下一个线程,等第一个线程执行完立即执行,用scheduleWithFixedDelay则从第7s开始准备执行下一个线程。

工作线程的执行过程:

工作线程会从DelayQueue取已经到期的任务去执行;

执行结束后重新设置任务的到期时间,再次放回DelayQueue

在这里插入图片描述



ScheduledThreadPoolExecutor使用

public class Test implements Runnable {
    Integer index;

    public Test(Integer index) {
        this.index = index;
    }

    @SneakyThrows
    @Override
    public void run() {
        System.out.println(Thread.currentThread().toString()+"  index:"+index+" time:"+System.currentTimeMillis()+"执行开始");
        Thread.sleep(10000);
    }
}
public class Testcase {

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        int i=0;
        ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(3, new ThreadPoolExecutor.CallerRunsPolicy());
//        threadPoolExecutor.schedule(new Test(i++),2,TimeUnit.SECONDS);
//        threadPoolExecutor.scheduleAtFixedRate(new Test(i),0,2,TimeUnit.SECONDS);
        threadPoolExecutor.scheduleWithFixedDelay(new Test(i),0,2,TimeUnit.SECONDS);
    }
}


ScheduledThreadPoolExecutor和timmer区别



版权声明:本文为weixin_43778555原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。