12

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?

4

2 に答える 2

29

最大の違いは、タイマーが単一のバックグラウンド スレッドですべてのタスクをスケジュールすることです。一方、ExecutorService は、(必要に応じて) タスクを実行するための新しいスレッドを作成します (指定したプールのサイズまで、タスクはキューに入れられます)。

于 2011-05-24T14:09:45.267 に答える
15

もう 1 つの違いは、キャッチされない例外があるかどうかです。タイマーの場合、バックグラウンド スレッドは終了しますが、元に戻りません。ScheduledExecutor を使用すると (シングル スレッド構成であっても)、ScheduledExecutor はキャッチされない例外の後も続行できます。タスクを処理するために、必要な数のスレッドが実行されていることを確認しようとします。

ScheduledExecutor は、進行状況を操作したい場合に備えて、future も生成します。

于 2011-05-24T16:31:34.653 に答える