Checking if a Java Timer is cancelled

半城伤御伤魂 提交于 2019-11-30 22:39:52

问题


Why is there no isCancelled method for a java.util.Timer object?

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.

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).


回答1:


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 Timers with ExecutorServices.

There's a ScheduledExecutorService interface specifically for scheduled executor services. Instantiate using one of the Executors.new... methods.



来源:https://stackoverflow.com/questions/13880202/checking-if-a-java-timer-is-cancelled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!