Timer在JDK1.0就引入了,由于timer是单线程,处理多个任务按照顺序执行,存在延时与设置定时器的时间有出入;并且可以能因为其中的某个任务的错误出现线程死掉影响后续任务执行。
ScheduledExecutorService为了弥补Timer的缺陷,jdk1.5中引入了并发包。Timer内部为一个线程,ScheduledExecutorService内部为线程池;继承基类Executor
据如下例子:Timer

图1中调用LanuchTimer是抛出运行时异常,后续中断不执行addOneTask;如图2;

如果使用ScheduledExecutorService则程序不会受异常中断运行;
如图:
scheduleAtFixedRate方法是按照固定频率去执行任务的。而scheduleWithFixedDelay方法则是按照固定的延迟去执行任务。
scheduleAtFixedRate()和scheduleWithFixedDelay方法参数是一样的。第一个参数是任务实例,第二个参数是延迟时间,第三个是间隔时间,第四个是时间单元
initalDelay表示延迟执行时间,delay循环间隔时间;


网友评论