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 中完成
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
