一、ScheduledExecutorService 设计思想
ScheduledExecutorService,是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。
需要注意,只有当调度任务来的时候,ScheduledExecutorService才会真正启动一个线程,其余时间ScheduledExecutorService都是c处于轮询任务的状态。
ScheduledExecutorService 中两种最常用的调度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。
ScheduleAtFixedRate :每次执行时间为上一次任务开始起向后推一个时间间隔。ScheduleAtFixedRate 是基于固定时间间隔进行任务调度
ScheduleWithFixedDelay: 每次执行时间为上一次任务结束起向后推一个时间间隔。ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。
二、示例
ScheduleAtFixedRate
1、任务
import java.util.Date;
class Task implements Runnable {
private String taskName;
Task(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println(taskName