检查Java Timer是否被取消 [英] Checking if a Java Timer is cancelled

查看:952
本文介绍了检查Java Timer是否被取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 isCancelled 方法/Timer.html\">java.util.Timer 对象?

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

推荐答案

如何确定你想要使用计时器?使用 ExecutorService 相反,它有 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 Timers with ExecutorServices.

有一个 ScheduledExecutorService 接口,专门用于计划的执行程序服务。使用 Executors.new ... 方法之一实例化。

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

这篇关于检查Java Timer是否被取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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