等待计时器在 Java 中完成

2022-01-22 00:00:00 timer synchronization java monitor

我正在使用 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.

相关文章