Executor并发框架

本文介绍了ScheduledExecutorService,用于定期执行任务或延迟任务。讲解了如何使用newScheduledThreadPool创建executor,以及scheduleAtFixedRate和scheduleWithFixedDelay的区别。此外,详细阐述了Future对象在异步执行中的作用,如何获取任务结果,以及如何取消任务执行。还提供了一个ExecutorExample,展示了如何创建和执行Callable任务。
摘要由CSDN通过智能技术生成

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 的任务是异步的,即程序不会等待当前任务执行完成,而是直接进

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值