完整类名:java.util.concurrent.ScheduledThreadPoolExecutor
1, 试用代码
package com.dosrain.shunc.trial.schedule;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class PoolTest {
public static void main(String[] args) {
ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()) + ": task-1 start");
pool.scheduleWithFixedDelay(new Task(), 0, 2, TimeUnit.SECONDS);
// 或者
pool.scheduleAtFixedRate(new Task(), 0, 2, TimeUnit.SECONDS);
}
}
class Task implements Runnable {
public static int counter=0;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void run() {
counter++;
System.out.println(Thread.currentThread().getName()
+ " " + counter + " " + sdf.format(new Date())
+ ": task-1 start");
int i=0;
if (counter == 2) {
i = 3;
} else {
i = 1;
}
try {
Thread.sleep(i * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
上面的代码中,为了说明问题,设计了这样一个处理,
第二次任务的运行时间为3秒,超出了预设的间隔时间,其余任务的运行时间均为1秒。
scheduleWithFixedDelay 结果:
pool-1-thread-1 1 2020-07-06 13:43:15: task-1 start
pool-1-thread-1 2 2020-07-06 13:43:18: task-1 start
pool-1-thread-1 3 2020-07-06 13:43:23: task-1 start
pool-1-thread-1 4 2020-07-06 13:43:26: task-1 start
pool-1-thread-1 5 2020-07-06 13:43:29: task-1 start
执行时间如下表:
任务序号 | 开始执行时间(秒) | 执行耗时(秒) | 间隔时间(秒) |
---|---|---|---|
1 | 15 | 1 | 2 |
2 | 18 | 3 | 2 |
3 | 23 | 1 | 2 |
4 | 26 | 1 | 2 |
5 | 29 | 1 | 2 |
scheduleAtFixedRate 结果:
2020-07-06 13:53:19: task-1 start
pool-1-thread-1 1 2020-07-06 13:53:19: task-1 start
pool-1-thread-1 2 2020-07-06 13:53:21: task-1 start
pool-1-thread-1 3 2020-07-06 13:53:24: task-1 start
pool-1-thread-1 4 2020-07-06 13:53:25: task-1 start
pool-1-thread-1 5 2020-07-06 13:53:27: task-1 start
pool-1-thread-1 6 2020-07-06 13:53:29: task-1 start
执行时间如下表:
任务序号 | 开始执行时间(秒) | 执行耗时(秒) | 间隔时间(秒) |
---|---|---|---|
1 | 19 | 1 | 2 |
2 | 21 | 3 | 2 |
3 | 24 | 1 | 2 |
4 | 25 | 1 | 2 |
5 | 27 | 1 | 2 |
5 | 29 | 1 | 2 |
2, 理解区别
- scheduleWithFixedDelay: 固定执行间隔时间,如果上一次执行耗时超过了预设的执行时间间隔,那么下一次会跳过,不会立即补算。
- scheduleAtFixedRate: 固定执行频率,如果上一次执行耗时超过了预设的执行时间间隔,那么下一次不会跳过,会立即补算。