Timer与ScheduledExecutorService
来源:互联网 发布:if you中文网络歌手 编辑:程序博客网 时间:2024/06/05 04:50
Timer与ScheduleExecutorService,二者都代表定时任务。
Timer:
public static void main(String[] args) {Timer timer = new Timer();//继承TimerTask抽象类,覆写run方法,表示一个任务MyTimerTask timerTask = new MyTimerTask();/* * schedule(TimerTask task, long delay, long period) * 延迟delay秒,每period秒执行定时任务 */timer.schedule(timerTask,1000,1000);// 执行定时任务}
timer.schedule()中需要一个TimerTask的参数,需要继承Timertask类并覆写run方法,定时任务会执行run方法
public class MyTimerTask extends TimerTask {@Overridepublic void run() {System.out.println("一次执行定时任务开始");try {System.out.println("任务执行中...");Thread.sleep(1500);} catch (InterruptedException e) {}System.out.println("一次任务执行结束");}}
ScheduledExecutorService:
public static void main(String[] args) {ScheduledExecutorService ses = Executors.newScheduledThreadPool(10);//创建一个定时任务的线程池/** * scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) * command:线程 * initialDelay:延期时间 * period:每个period毫秒执行一次 * TimeUnit:标注前面两个参数的单位(s,mm,min等) * *///执行定时任务ses.scheduleAtFixedRate(new Runnable(){public void run(){System.out.println(System.currentTimeMillis());}}, 1000, 1000,TimeUnit.MILLISECONDS);//与上面的任务并行,不冲突ses.scheduleAtFixedRate(new Runnable(){public void run(){System.out.println("hello world");}}, 1000, 1000, TimeUnit.MILLISECONDS);}
Timer与ScheduledExecutorService的异同比计较
所有的TimerTask都是单线程任务,而ScheduledExecutorService是多线程任务,每一个任务都是一个线程,任务与任务之间是并行状态
Timer的缺点:
1、由于是单线程,所以如果当一个任务执行的时间太长,会延迟其他任务的执行
2、当TimerTask抛异常时会终止整个定时任务,使整个Timer都取消了,从而未执行的TimerTask也被终止,而ScheduledExecutorService是多线程,
当一个任务线程抛异常,不会影响其他任务线程
所以推荐使用ScheduledExecutorService
阅读全文
0 0
- timer与ScheduledExecutorService
- Timer与ScheduledExecutorService
- Timer与ScheduledExecutorService
- Timer/TimerTask与ScheduledExecutorService
- Timer与ScheduledExecutorService
- Timer与ScheduledExecutorService 的使用和区别
- Timer与ScheduledExecutorService的使用和区别
- Timer与ScheduledExecutorService间的选择
- Timer与ScheduledExecutorService间的抉择
- Timer与ScheduledExecutorService间的抉择
- Java之——Timer与ScheduledExecutorService
- Java学习:Timer与ScheduledExecutorService的区别
- Timer与ScheduledExecutorService间的抉择
- Java学习:Timer与ScheduledExecutorService的区别
- ScheduledExecutorService与Timer的方法比较
- Timer与ScheduledExecutorService定时器的比较及其简单事例
- timer和ScheduledExecutorService延时器与定时器的使用
- Timer和ScheduledExecutorService间决择
- algo_FISTA(fast shrinkage-thresholding algorithm)
- matlab常用快捷键
- 教你如何绕过百度客戶端快速下載百度云盘的电影等文件,仅适应MAC OSx
- jedis源码分析和使用
- ssm 拦截器
- Timer与ScheduledExecutorService
- springboot+mybatis分页插件pageHelper的配置与使用
- java内存泄漏
- MyBatis动态sql_where查询条件
- AC自动机模板
- Linux下安装Samba共享文件
- 应用程序打包神器Inno setup
- LeetCode——Palindrome Linked List
- mysql创建高性能的索引