Difference between TimerTask and Executors.newScheduledThreadPool(1)

后端 未结 2 461
北恋
北恋 2021-02-07 20:38

I need to schedule some work to be done in the future. I can do it in 2 ways:

  1. Create a TimerTask and execute timer.schedule(...);

    <
2条回答
  •  后悔当初
    2021-02-07 20:53

    One other difference is if there is an uncaught exception. In case of a Timer, the background thread is terminated but it is not brought back up. With a ScheduledExecutor (even with a single thread configuration), the ScheduledExecutor can continue after an uncaught exception. It tries to ensure the desired number of threads are running to process the tasks.

    The ScheduledExecutor also produces a future in case you want to interact with the progress.

提交回复
热议问题