简述
- SheduleExecutorService 是基于线程池设计的定时任务类,每个调度任务都是会在线程池中分配到一个线程去执行,任务是并行的;
- 只有当调度任务运行时,ScheduledExecutorService 才会真正启动一个线程,其余时间ScheduledExecutorService都是处于轮询任务的状态;
重要方法
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
Timer缺点
- Timer不支持多线程。全部挂在Timer下的任务都是单线程的,任务仅仅能串行运行。假设当中一个任务运行时间过长。会影响到其它任务的运行,然后就可能会有各种接踵而来的问题。
- Timer的线程不捕获异常。TimerTask假设抛出异常,那么Timer唯一的进程就会挂掉,这样挂在Timer下的全部任务都会无法继续运行。
参考