线程池(三)--ScheduledThreadPoolExecutor

什么是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区别

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值