线程池(5)Executors.newScheduledThreadPool
2024-09-04 10:43:52
例子1(scheduleAtFixedRate):延迟2秒后,每隔3秒执行1次
ScheduledExecutorService es = Executors.newScheduledThreadPool(5);
log.info("开始时间");
Runnable syncRunnable = new Runnable() {
@Override
public void run() {
log.info(Thread.currentThread().getName());
}
};
es.scheduleAtFixedRate(syncRunnable, 2000, 3000, TimeUnit.MILLISECONDS);
运行结果:
10:49:22.495 开始时间
10:49:24.500 pool-1-thread-1
10:49:27.499 pool-1-thread-1
10:49:30.500 pool-1-thread-2
10:49:33.500 pool-1-thread-1
10:49:36.501 pool-1-thread-3
10:49:39.500 pool-1-thread-2
10:49:42.500 pool-1-thread-2
10:49:45.500 pool-1-thread-1
10:49:48.501 pool-1-thread-1
10:49:51.501 pool-1-thread-1
10:49:54.501 pool-1-thread-4
10:49:57.501 pool-1-thread-2
10:50:00.502 pool-1-thread-2
10:50:03.502 pool-1-thread-3
10:50:06.502 pool-1-thread-3
10:50:09.502 pool-1-thread-3
10:50:12.503 pool-1-thread-5
10:50:15.503 pool-1-thread-5
10:50:18.503 pool-1-thread-5
10:50:21.503 pool-1-thread-5
10:50:24.503 pool-1-thread-3
10:50:27.503 pool-1-thread-2
10:50:30.503 pool-1-thread-1
10:50:33.504 pool-1-thread-4
10:50:36.504 pool-1-thread-5
10:50:39.504 pool-1-thread-5
10:50:42.504 pool-1-thread-2
例子2(scheduleWithFixedDelay):延迟5秒后,每个任务执行完后延迟3秒在执行1次
ScheduledExecutorService es = Executors.newScheduledThreadPool(5);
log.info("开始时间");
Runnable syncRunnable = new Runnable() {
@Override
public void run() {
log.info(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
es.scheduleWithFixedDelay(syncRunnable, 5000, 3000, TimeUnit.MILLISECONDS);
运行结果:
11:10:27.773 开始时间
11:10:32.778 pool-1-thread-1
11:10:36.779 pool-1-thread-1
11:10:40.780 pool-1-thread-2
11:10:44.781 pool-1-thread-1
11:10:48.783 pool-1-thread-3
11:10:52.785 pool-1-thread-3
11:10:56.785 pool-1-thread-4
11:11:00.787 pool-1-thread-4
11:11:04.788 pool-1-thread-4
11:11:08.789 pool-1-thread-4
11:11:12.790 pool-1-thread-3
11:11:16.792 pool-1-thread-1
本来是每隔3秒执行的,但是,由于某个任务处理时间过长,导致延后。本例是延后1秒,即4秒。
总结:scheduleAtFixedRate与scheduleWithFixedDelay区别
scheduleAtFixedRate:不管任务是否执行完了,在3秒内必须执行
scheduleWithFixedDelay:等任务执行完了,在等3秒后执行
因此,scheduleWithFixedDelay 非常有用。
最新文章
- python 获取当前目录下文件(转)
- sublime text 个性设置
- iSight集成Adams/View:Adams组件
- 洛谷P3366 【模板】最小生成树
- 何为“精通Java”
- linux 静态库、共享库
- php base64_decode 解码方法
- 嵌入式 -- WINKHUB 边信道攻击 (NAND Glitch)
- org.openqa.selenium.remote.SessionNotFoundException: The FirefoxDriver cannot be used after quit() was called.
- Encoding 类别
- 2019-04-16 SpringMVC 学习笔记
- 2017(5)软件架构设计,web系统的架构设计,数据库系统,分布式数据库
- Java编译与反编译
- [转]Laravel 数据库实例教程 —— 使用查询构建器实现对数据库的高级查询
- [编程笔记]第二章 C语言预备知识
- kafka可视化客户端工具(Kafka Tool)的基本使用
- perl 函数
- Python调用大漠插件
- 【leetcode】278. First Bad Version
- Oracle行列转换小结