Java Timer vs ExecutorService? [英] Java Timer vs ExecutorService?
问题描述
我有代码,我使用 java.util.timer
安排任务。我环顾四周,看到 ExecutorService
可以做同样的事情。所以这个问题,你有没有使用Timer和 ExecutorService
来安排任务,一个人使用另一个人的好处是什么?
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?
还想检查是否有人使用了 Timer
类并遇到了 ExecutorService
解决的任何问题他们。
Also wanted to check if anyone had used the Timer
class and ran into any issues which the ExecutorService
solved for them.
推荐答案
根据 Java实践中的并发:
-
计时器
可能对系统时钟ScheduledThreadPoolExecutor
不是。 -
计时器
只有一个执行线程,因此长时间运行的任务可以延迟其他任务。ScheduledThreadPoolExecutor
可以配置任意数量的线程。此外,如果需要,您可以完全控制已创建的线程(通过提供ThreadFactory
)。 - <$ c中抛出的运行时异常$ c> TimerTask 杀死一个线程,从而使
Timer
死:-( ...即计划任务不再运行。ScheduledThreadExecutor
不仅可以捕获运行时异常,还可以根据需要处理它们(通过从afterExecute
方法> ThreadPoolExecutor )。抛出异常的任务将被取消,但其他任务将继续运行。
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.
如果您可以使用 ScheduledThreadExecutor
而不是计时器
,请执行此操作。
If you can use ScheduledThreadExecutor
instead of Timer
, do so.
还有一件事......当Java 1.4库中没有 ScheduledThreadExecutor
时,有一个 JSR 166( java.util.concurrent
)的后端到Java 1.2,1.3,1.4 ,其中包含 ScheduledT hreadExecutor
class。
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 Timer vs ExecutorService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!