问题描述
为什么对象?
Why is there no isCancelled
method for a java.util.Timer object?
如果Timer没有被取消,我想安排一个任务,并运行它直接(在同一个线程上),如果它已被取消。
I would like to schedule a task if the Timer has not been cancelled, and run it directly (on the same thread) if it has been cancelled.
是捕获 IllegalStateException
的唯一选项如果Timer已被取消,可能会发生? (抓住 IllegalStateException
感觉不对。)
Is the only option to catch the IllegalStateException
that might occur if the Timer already has been cancelled? (It feels wrong to catch an IllegalStateException
).
推荐答案
如何确定你想要使用计时器
?使用相反,它有 isShutdown
并且还有很多其他好处可以启动。从Java 5开始的一般建议是用 ExecutorService
替换 Timer
s。
How sure are you that you want to use Timer
? Use ExecutorService
instead, which has isShutdown
and has a slew of other benefits to boot. A general recommendation as of Java 5 has been to replace Timer
s with ExecutorService
s.
有一个 ScheduledExecutorService
接口,专门用于计划的执行程序服务。使用 Executors.new ...
方法之一实例化。
There's a ScheduledExecutorService
interface specifically for scheduled executor services. Instantiate using one of the Executors.new...
methods.
这篇关于检查Java Timer是否被取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!