2.4 ScheduledExecutor
当我们有一个需要定期运行的任务或者我们希望延迟某个任务时,就会使用此类型的 executor。
ScheduledExecutorService scheduledExecService = Executors.newScheduledThreadPool(1);
可以使用 scheduleAtFixedRate 或 scheduleWithFixedDelay 在 ScheduledExecutor 中定期的执行任务。
scheduledExecService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
scheduledExecService.scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit)
这两种方法的主要区别在于它们对连续执行定期任务之间的延迟的应答。
scheduleAtFixedRate:无论前一个任务何时结束,都以固定间隔执行任务。
scheduleWithFixedDelay:只有在当前任务完成后才会启动延迟倒计时。
[](()3. 对于 Future 对象的理解
可以使用 executor 返回的 java.util.concurrent.Future 对象访问提交给 executor 的任务的结果。 Future 可以被认为是 executor 对调用者的响应。
Future result = executorService.submit(callableTask);
如上所述,提交给 executor 的任务是异步的,即程序不会等待当前任务执行完成,而是直接进