scheduleWithFixedDelay与scheduleAtFixedRate的区别
时间: 2024-01-19 07:18:13 浏览: 36
scheduleWithFixedDelay和scheduleAtFixedRate是ScheduledThreadPoolExecutor类中的两个方法,用于在固定的时间间隔内执行任务。它们的区别在于任务的调度方式和下次任务开始时间的计算方式。
1. scheduleWithFixedDelay方法:
- 调度方式:在上一次任务执行完成后,等待固定的时间间隔,然后再执行下一次任务。
- 下次任务开始时间的计算方式:以上一次任务的结束时间为基准,加上固定的时间间隔,作为下一次任务的开始时间。
2. scheduleAtFixedRate方法:
- 调度方式:在上一次任务开始后,等待固定的时间间隔,然后再执行下一次任务。
- 下次任务开始时间的计算方式:以上一次任务的开始时间为基准,加上固定的时间间隔,作为下一次任务的开始时间。
这两种调度方式的区别在于对任务执行时间的处理方式。scheduleWithFixedDelay会等待固定的时间间隔,无论上一次任务执行的时间长短,而scheduleAtFixedRate会按照固定的时间间隔执行任务,不考虑上一次任务的执行时间。
范例:
```java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduleExample {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// 使用scheduleWithFixedDelay方法
executor.scheduleWithFixedDelay(() -> {
System.out.println("scheduleWithFixedDelay: " + System.currentTimeMillis());
try {
Thread.sleep(2000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 0, 1000, TimeUnit.MILLISECONDS);
// 使用scheduleAtFixedRate方法
executor.scheduleAtFixedRate(() -> {
System.out.println("scheduleAtFixedRate: " + System.currentTimeMillis());
try {
Thread.sleep(2000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 0, 1000, TimeUnit.MILLISECONDS);
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)