线程池 ScheduledExecutorService (1) 延迟 / 周期执行线程池
文章目录
ScheduledExecutorService 简述
1、public interface ScheduledExecutorService extends ExecutorService 延迟或定期执行任务。
2、schedule 方法使用各种延迟创建任务,并返回一个可用于取消或检查执行的任务对象
3、scheduleAtFixedRate 和 scheduleWithFixedDelay 方法创建并执行某些在取消前一直定期运行的任务
4、所有的 schedule 方法都接受相对延迟和周期作为参数,而不是绝对的时间或日期
5、SheduleExecutorService 是JDK 1.5出来的,比以前的 Timer 性能好
Method Description |
---|
<V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) 创建并执行在给定延迟后启用的单次操作。 |
ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) 创建并执行在给定延迟后启用的单次操作。 |
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 创建并执行在给定的初始延迟之后,以给定的时间间隔执行周期性动作。 即在 initialDelay 初始延迟后,initialDelay+period 执行第一次,initialDelay + 2 * period 执行第二次,依次类推。 |
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 创建并执行在给定的初始延迟之后首先启用的定期动作,随后上一个执行的终止和下一个执行的开始之间给定的延迟。 |
对象创建方式
1、此实例最快捷的方式是使用Executors
工具来创建:
static
ScheduledExecutorServicenewScheduledThreadPool(int corePoolSize)
:创建一个线程池,它可安排在给定延迟后运行任务或者定期地执行任务。 corePoolSize - 池中所保存的线程数,即使线程是空闲的也包括在内。
static
ScheduledExecutorServicenewSingleThreadScheduledExecutor()
:创建一个单线程
执行程序,它可安排在给定延迟后运行命令或者定期地执行任务。可保证顺序地执行各个任务,并且在任意给定的时间不会有多个线程是活动的。 同样这是一个无界的任务队列,即虽然线程只有一个,但是新增的任务会在队列中排队等待执行。
2、此外除了使用 Executors 创建之外,推荐使用 ScheduledExecutorService 的实现类 ScheduledThreadPoolExecutor
schedule Runnable
1、ScheduledFuture<?> schedule(Runnable command,long delay,TimeUnit unit) :创建并执行在给定延迟后启用的一次性
操作。
2、参数:command - 要执行的任务;delay - 从现在开始延迟执行的时间;unit - 延迟参数的时间单位
schedule Callable
1、ScheduledFuture schedule(Callable callable, long delay,TimeUnit unit):创建并执行在给定延迟后启用的 一次性
操作
2、参数:callable - 要执行的功能;delay - 从现在开始延迟执行的时间;unit - 延迟参数的时间单位
scheduleAtFixedRate
1、ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay, long period, TimeUnit unit):创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期重复执行
;
2、在 initialDelay 后开始执行,然后在 initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。意思是下一次执行任务的时间与任务执行过程花费的时间无关,只与period有关!
3、如果此任务的任何一个执行要花费比其周期更长的时间,则将推迟
后续执行,但不会同时执行
。
4、如果任务的任何一个执行遇到异常
,则后续执行都会被取消
。否则,只能通过执行程序的取消或终止方法来终止该任务。
5、参数:command - 要执行的任务;initialDelay - 首次执行的延迟时间;period - 连续执行之间的周期;unit - initialDelay 和 period 参数的时间单位
scheduleWithFixedDelay
1、ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,TimeUnit unit):创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。
2、与 scheduleFixedDelay 区别仅仅在于前后两次任务执行的时间间隔不同而已