定时任务ScheduledThreadPoolExecutor:

  1. 介绍:
    之前我们讲的ThreadPoolExecutor是java的普通线程池。而ScheduledThreadPoolExecutor是java提供的定时任务线程池。

  2. 使用:

常用方法
java.util.concurrent.ScheduledThreadPoolExecutor#schedule 定时任务
java.util.concurrent.ScheduledThreadPoolExecutor#scheduleAtFixedRate 固定速率连续执行
java.util.concurrent.ScheduledThreadPoolExecutor#scheduleWithFixedDelay非固定速率连续执行
java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue延迟队列

  1. scheduleAtFixedRate 和scheduleWithFixedDelay区别
    实例代码:gitee仓库地址
    部分代码
//测试类
public class Test {
   
    public static void main(String[] args) {
   
        final ScheduleServiceImple scheduleServiceImple = new ScheduleServiceImple();
        scheduleServiceImple.startJob(5);
    }
}


public class ScheduleServiceImple implements ScheduledService {
   
    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);

    @Override
    public void startJob(int seconds) {
   
        executorService.scheduleAtFixedRate(new Monitor(), 0, seconds, TimeUnit.SECONDS);
        //executorService.scheduleWithFixedDelay(new Monitor(), 0, seconds, TimeUnit.SECONDS);
    }

    @Override
    public void shutdown() {
   

    }
}

//执行类
public class Monitor implements Runnable {
   
    @Override
    public void run() {
   
        System.out.println(Thread.currentThread().getName() + "Start Time" + new Date());
        System.out.println("java.version:" + System.getProperty("java.version"));
        System.out.println("java.class.path:" + System.getProperty("java.class.path"));
        System.out.println("user.dir" + System.getProperty("user.dir"));
        try {
   
        	//等待5秒结束
            Thread.sleep(5000);
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "End Time" + new Date());
        System.out.println("===============");
    }
}

解释:

固定速率连续执行:延迟时间内没有执行完,任务会启动多个并行执行
非固定速率连续执行:需要等待任务完成后在进行延迟启动任务

  • scheduleWithFixedDelay

  • scheduleAtFixedRate