在 Java 中等待计时器完成 [英] Waiting for a Timer to finish in Java

查看:33
本文介绍了在 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?)

我可以引入外部同步机制,但我看不出它们如何涵盖所有情况.比如我在任务内的某个Monitor上同步,我还是会怀念任务刚开始执行但没拿monitor的情况.

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 中等待计时器完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆