使用java自带的定时任务ScheduledThreadPoolExecutor
2024-09-23 10:13:27
ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类;
JDK api里是这么说的:
ThreadPoolExecutor
,它可另行安排在给定的延迟后运行命令,或者定期执行命令。需要多个辅助线程时,或者要求 ThreadPoolExecutor
具有额外的灵活性或功能时,此类要优于 Timer
。
一旦启用已延迟的任务就执行它,但是有关何时启用,启用后何时执行则没有任何实时保证。按照提交的先进先出 (FIFO) 顺序来启用那些被安排在同一执行时间的任务。
---------------
平时我们在执行一个定时任务时,会采用Time,和TimeTask来组合处理;
但是Timer和TimerTask存在一些缺陷:
1:Timer只创建了一个线程。当你的任务执行的时间超过设置的延时时间将会产生一些问题。
2:Timer创建的线程没有处理异常,因此一旦抛出非受检异常,该线程会立即终止。
JDK 5.0以后推荐使用ScheduledThreadPoolExecutor。该类属于Executor Framework,它除了能处理异常外,还可以创建多个线程解决上面的问题
package timer; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit; public class Test
{
static ScheduledThreadPoolExecutor stp = null;
static int index; private static String getTimes() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
Date date = new Date();
date.setTime(System.currentTimeMillis());
return format.format(date);
} private static class MyTask implements Runnable { @Override
public void run() {
index++;
System.out.println("2= " + getTimes()+" " +index);
// if(index >=10){
// stp.shutdown();
// if(stp.isShutdown()){
// System.out.println("停止了????");
// }
// }
}
}
public static void main(String[] args)
{
stp = new ScheduledThreadPoolExecutor(5);
MyTask mytask = new MyTask();
//mytask为线程,2是首次执行的延迟时间,最后一个参数为时间单位
// stp.schedule(mytask, 2, TimeUnit.SECONDS);
// 首次执行延迟2秒,之后的执行周期是1秒
// stp.scheduleAtFixedRate(mytask, 2, 1,TimeUnit.SECONDS );
//首次执行延迟2秒,之后从上一次任务结束到下一次任务开始时1秒
stp.scheduleWithFixedDelay(mytask, 2, 1, TimeUnit.SECONDS); } }
最新文章
- 将 VMware 最小化到系统托盘
- java学习第19天(异常)
- DFS security warning and use group policy to set up internet security zones
- 模板题 codevs 1993 草地排水 想学习的请看链接
- C++学习笔记24:makefile文件
- Intrinsics头文件与SIMD指令集、Visual Studio版本对应表(转)
- State状态设计模式
- am,pm时间转换
- 给Android程序员的六个建议
- complex(x):创建一个复数
- JDK8在Java转让Javascript脚本引擎动态地定义和运行代码
- MySQL replace into 说明(insert into 增强版)
- CODE[VS]-求和-整数处理-天梯青铜
- Apache无法启动提示the requested operation has failed
- vmstat 命令详解
- 输入、输出与Mad Libs 游戏。
- Spring的IOC注解开发入门2
- [luogu1552][派遣]
- BZOJ5177 : [Jsoi2013]贪心的导游
- Linux 性能监控之CPU&;内存&;I/O监控Shell脚本2