Waiting for a Timer to finish in Java(等待计时器在 Java 中完成)
问题描述
我正在使用 java.util.定时器 来安排一个周期性的任务.在某一时刻,我想关闭它,然后等待它完成.
I'm using java.util.Timer to schedule a periodic task. At one point, I'd like to shut it down, and wait for it to finish.
Timer.cancel() 将阻止任何未来的任务运行.我如何确保当前没有运行任何任务(或者等待它们运行?)
Timer.cancel() will prevent any future tasks from running. How do I make sure any tasks are not running at the moment (or wait for them if they are?)
我可以引入外部同步机制,但我看不出它们如何涵盖所有情况.例如,如果我在任务中的某个监视器上进行同步,我仍然会错过任务刚开始执行但没有占用监视器的情况.
I can introduce external synchronization mechanisms, but I don't see how they can cover all cases. For example, if I synchronize on some Monitor within the task, I still miss the case when the task just started executing but didn't take the monitor.
等待所有任务真正完成(包括当前正在运行的任务)的推荐做法是什么?
What is the recommended practice for waiting until all tasks are really done, including currently running tasks?
推荐答案
最好使用 ScheduledExecutorService 而不是 Timer 来安排您的定期任务.ScheduledExecutorService 提供了一个shutdown() 方法,它将执行任何挂起的任务.然后您可以调用 awaitTermination() 来等待 shutdown() 完成.
You would be better using an ScheduledExecutorService instead of a Timer to schedule your periodic task. ScheduledExecutorService provides a shutdown() method that will execute any pending tasks. You can then call awaitTermination() to wait for shutdown() to finish.
这篇关于等待计时器在 Java 中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:等待计时器在 Java 中完成


- 获取数字的最后一位 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01