Java 定时器 vs ExecutorService? [英] Java Timer vs ExecutorService?
问题描述
我有使用 java.util.Timer
安排任务的代码.我环顾四周,看到 ExecutorService
可以做同样的事情.所以这个问题,你有没有使用 Timer
和 ExecutorService
来安排任务,一个使用另一个的好处是什么?
还想检查是否有人使用过 Timer
类并遇到 ExecutorService
为他们解决的任何问题.
根据Java并发实践:>
Timer
可以对系统时钟的变化敏感,ScheduledThreadPoolExecutor
不是.Timer
只有一个执行线程,所以长时间运行的任务会延迟其他任务.ScheduledThreadPoolExecutor
可以配置任意数量的线程.此外,如果需要,您可以完全控制创建的线程(通过提供ThreadFactory
).TimerTask
中抛出的运行时异常会杀死该线程,从而使Timer
死亡 :-( ... 即计划任务将不再运行.ScheduledThreadExecutor
不仅可以捕获运行时异常,而且还可以让您根据需要处理它们(通过覆盖ThreadPoolExecutor
中的afterExecute
方法).抛出异常的任务将被取消,但是其他任务将继续运行.
如果您可以使用 ScheduledThreadExecutor
而不是 Timer
,请这样做.
还有一件事...虽然 ScheduledThreadExecutor
在 Java 1.4 库中不可用,但有一个 将 JSR 166 (java.util.concurrent
) 向后移植到具有 ScheduledThreadExecutor
类的 Java 1.2、1.3、1.4.
I have code where I schedule a task using java.util.Timer
. I was looking around and saw ExecutorService
can do the same. So this question here, have you used Timer
and ExecutorService
to schedule tasks, what is the benefit of one using over another?
Also wanted to check if anyone had used the Timer
class and ran into any issues which the ExecutorService
solved for them.
According to Java Concurrency in Practice:
Timer
can be sensitive to changes in the system clock,ScheduledThreadPoolExecutor
isn't.Timer
has only one execution thread, so long-running task can delay other tasks.ScheduledThreadPoolExecutor
can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providingThreadFactory
).- Runtime exceptions thrown in
TimerTask
kill that one thread, thus makingTimer
dead :-( ... i.e. scheduled tasks will not run anymore.ScheduledThreadExecutor
not only catches runtime exceptions, but it lets you handle them if you want (by overridingafterExecute
method fromThreadPoolExecutor
). Task which threw exception will be canceled, but other tasks will continue to run.
If you can use ScheduledThreadExecutor
instead of Timer
, do so.
One more thing... while ScheduledThreadExecutor
isn't available in Java 1.4 library, there is a Backport of JSR 166 (java.util.concurrent
) to Java 1.2, 1.3, 1.4, which has the ScheduledThreadExecutor
class.
这篇关于Java 定时器 vs ExecutorService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!