本文介绍了等待Timer在Java中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用安排定期任务。有一次,我想关闭它,等待它完成

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() 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?

推荐答案

你最好使用而不是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.

这篇关于等待Timer在Java中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 15:46