本文共 1637 字,大约阅读时间需要 5 分钟。
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 { @Override public 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
转载地址:http://ejcrj.baihongyu.com/