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); } }

最新文章

  1. 将 VMware 最小化到系统托盘
  2. java学习第19天(异常)
  3. DFS security warning and use group policy to set up internet security zones
  4. 模板题 codevs 1993 草地排水 想学习的请看链接
  5. C++学习笔记24:makefile文件
  6. Intrinsics头文件与SIMD指令集、Visual Studio版本对应表(转)
  7. State状态设计模式
  8. am,pm时间转换
  9. 给Android程序员的六个建议
  10. complex(x):创建一个复数
  11. JDK8在Java转让Javascript脚本引擎动态地定义和运行代码
  12. MySQL replace into 说明(insert into 增强版)
  13. CODE[VS]-求和-整数处理-天梯青铜
  14. Apache无法启动提示the requested operation has failed
  15. vmstat 命令详解
  16. 输入、输出与Mad Libs 游戏。
  17. Spring的IOC注解开发入门2
  18. [luogu1552][派遣]
  19. BZOJ5177 : [Jsoi2013]贪心的导游
  20. Linux 性能监控之CPU&内存&I/O监控Shell脚本2

热门文章

  1. 使用Angular和Nodejs搭建聊天室
  2. [原] Android performClick无效,UI线程理解
  3. Highways(prim & MST)
  4. NGINX userid 分析、解码
  5. Windows环境下的jekyll本地搭建
  6. 【Python】python代码如何调试?
  7. Xenomai 安装准备工作
  8. css整个页面离顶部的距离
  9. Cannot change version of project facet Dynamic web module to 2.5
  10. CUDA学习笔记(四)——CUDA性能