Difference between TimerTask and Executors.newScheduledThreadPool(1)

筅森魡賤 提交于 2019-12-03 16:36:36

问题


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. Use Executors.newScheduledThreadPool(1):

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    ScheduledFuture <?> scheduleHandle = scheduler.schedule(pushExternalRunnable,  
            runScheduleDate.getTime() - now.getTime(), TimeUnit.MILLISECONDS);
    

What is the difference between these 2 ways of scheduling the work in the future?


回答1:


The biggest difference is that the Timer will schedule all of its tasks on a single background thread. The ExecutorService, on the other hand, will create new threads (if necessary) to run the tasks (up to the size of the pool you specify, at which point tasks will be queued.)




回答2:


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.



来源:https://stackoverflow.com/questions/6111645/difference-between-timertask-and-executors-newscheduledthreadpool1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!