Java使用Timer和ScheduledThreadPoolExecutor执行定时任务 定时任务是在指定时间执行程序,或周期性执行计划任务.Java中实现定时任务的方法有很多,主要JDK自带的一些方法以及开源程序如Qurtz. >>Timer和TimerTask Timer只是充当了一个执行者的角色,真正的任务逻辑是通过一个叫做TimerTask的抽象类完成的,TimerTask也是java.util包下面的类,它是一个实现了Runnable接口的抽象类,包含一个抽象方法run( )方法,…
推荐还是用第二种方法,即用ScheduledThreadPoolExecutor,因为它不需要像timer那样需要在里面再用一个线程池来保证计时的准确.(前提是线程池必须要大于1个线程) 1.timer中用线程池来执行任务,可以保证开始执行时间的准确,具体结束时间要以任务需要执行时间为准.如果未使用线程池,执行时间将被任务执行时间所影响. package timer; import java.text.SimpleDateFormat; import java.util.Date; import…
//ScheduledThreadPoolExecutor每三秒执行一次 public static void main(String[] args) {        ScheduledThreadPoolExecutor  scheduled = new ScheduledThreadPoolExecutor(2);        scheduled.scheduleAtFixedRate(new Runnable() {            int i = 0;            @…
Timer 基于单线程.系统时间实现的延时.定期任务执行类.具体可以看下面红色标注的代码. public class Timer { /** * The timer task queue. This data structure is shared with the timer * thread. The timer produces tasks, via its various schedule calls, * and the timer thread consumes, executing…
JDK 1.5开始提供ScheduledThreadPoolExecutor类,ScheduledThreadPoolExecutor类继承ThreadPoolExecutor类重用线程池实现了任务的周期性调度功能.在JDK 1.5之前,实现任务的周期性调度主要使用的是Timer类和TimerTask类.本文,就简单介绍下ScheduledThreadPoolExecutor类与Timer类的区别,ScheduledThreadPoolExecutor类相比于Timer类来说,究竟有哪些优势,以…
refs: https://blog.csdn.net/wenzhi20102321/article/details/78681379 对比一下Timer和ScheduledThreadPoolExecutor: Timer ScheduledThreadPoolExecutor 单线程 多线程 单个任务执行时间影响其他任务调度 多线程,不会影响 基于绝对时间 基于相对时间 一旦执行任务出现异常不会捕获,其他任务得不到执行 多线程,单个任务的执行不会影响其他线程 所以,在JDK1.5之后,应该没…
介绍 自JDK1.5开始,JDK提供了ScheduledThreadPoolExecutor类来支持周期性任务的调度.在这之前的实现需要依靠Timer和TimerTask或者其它第三方工具来完成.但Timer有不少的缺陷: Timer是单线程模式: 如果在执行任务期间某个TimerTask耗时较久,那么就会影响其它任务的调度: Timer的任务调度是基于绝对时间的,对系统时间敏感: Timer不会捕获执行TimerTask时所抛出的异常,由于Timer是单线程,所以一旦出现异常,则线程就会终止,…
JUC源码分析-线程池篇(三)ScheduledThreadPoolExecutor ScheduledThreadPoolExecutor 继承自 ThreadPoolExecutor.它主要用来在给定的延迟之后运行任务,或者定期执行任务.ScheduledThreadPoolExecutor 的功能与 Timer 类似,但 Timer 对应的是单个后台线程,而 ScheduledThreadPoolExecutor 可以在构造函数中指定多个对应的后台线程数. JUC源码分析-线程池篇(三)T…
摘要:JDK 1.5开始提供Scheduled Thread PoolExecutor类,Scheduled Thread Pool Executor类继承Thread Pool Executor类重用线程池实现了任务的周期性调度功能. 本文分享自华为云社区<[高并发]ScheduledThreadPoolExecutor与Timer的区别和简单示例>,作者:冰 河 . JDK 1.5开始提供ScheduledThreadPoolExecutor类,ScheduledThreadPoolExe…
概要 前面分别介绍了"Java多线程基础"."JUC原子类"和"JUC锁".本章介绍JUC的最后一部分的内容--线程池.内容包括:线程池架构图线程池示例 转载请注明出处:http://www.cnblogs.com/skywang12345/p/3509903.html 线程池架构图 线程池的架构图如下: 1. Executor 它是"执行者"接口,它是来执行任务的.准确的说,Executor提供了execute()接口来执行…