java.util.Timer: Is it deprecated?

前端 未结 6 1495
既然无缘
既然无缘 2020-12-01 08:26

I read in a comment to this answer and in many other questions about scheduling (sorry, no references) that java.util.Timer is deprecated. I really hope not sin

6条回答
  •  星月不相逢
    2020-12-01 09:09

    As others have mentioned, no it is not deprecated but I personally always use ScheduledExecutorService instead as it offers a richer API and more flexibility:

    • ScheduledExecutorService allows you to specify the number of threads whereas Timer always uses a single thread.
    • ScheduledExecutorService can be constructed with a ThreadFactory allowing control over thread aspects other than the name / daemon status (e.g. priority, ThreadGroup, UncaughtExceptionHandler).
    • ScheduledExecutorService allows tasks to be scheduled with fixed delay as well as at a fixed rate.
    • ScheduledExecutorService accepts Callable / Runnable as it's unit of work, meaning that you don't need to subclass TimerTask specifically to use it; i.e. you could submit the same Callable implementation to a regular ExecutorService or a ScheduledExecutorService.

提交回复
热议问题