背景:
Timer類負責延遲任務和周期任務,但是Timer存在一些缺陷,是以應該考慮使用ScheduledThreadPoolExecutor來代替它。
Timer缺陷:
1、Timer在執行所有定時任務時隻會建立一個線程。如果某個任務的執行時間過長,那麼将破壞其他TimerTask的定時精确性。
2、如果TimerTask抛出了一個未檢查異常,那麼Timer将表現出糟糕行為。Timer線程并不捕獲異常,是以TimerTask抛出未檢查異常時将終止定時線程。
時鐘排程差別:
Timer支援基于絕對時間而不是相對時間的排程機制,是以任務的執行對系統時鐘變化很敏感,而ScheduledThreadPoolExecutor 隻支援基于相對時間的排程。
代碼示例:
package com.csdn.test.timer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class TestScheTask
{
private static final int TRY_SEND_DATA_PERIOD = 2000;
// 重試間隔時間(毫秒)
private static final int TIMEOUT = 300000;
// 機關統一為毫秒
private static final TimeUnit UNIT = TimeUnit.MILLISECONDS;
private static final int MAX_TIME = 5;
private volatile AtomicBoolean isFinish = new AtomicBoolean(false);
private volatile CountDownLatch done = new CountDownLatch(1);
private int scheduledES_count1 = 0;
private int scheduledES_count2 = 0;
private int timer_count1 = 0;
private int timer_count2 = 0;
public void scheduleTaskByScheduledES()
{
// 單線程線程池
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleAtFixedRate(new Runnable()
{
@Override
public void run()
{
boolean isOk = isFinish.get();
if (!isOk)
{
System.out.println("ScheduleTaskByScheduledES: try start ... count1 is: " + scheduledES_count1);
scheduledES_count1 ++;
if (scheduledES_count1 > 1)
{
throw new RuntimeException("current count1 is: " + scheduledES_count1);
}
if (scheduledES_count1 > MAX_TIME)
{
isFinish.getAndSet(true);
done.countDown();
System.out.println("Scheduled thread: end success");
}
}
}
}, 0, TRY_SEND_DATA_PERIOD, UNIT);
exec.scheduleAtFixedRate(new Runnable()
{
@Override
public void run()
{
boolean isOk = isFinish.get();
if (!isOk)
{
System.out.println("ScheduleTaskByScheduledES: try start ... count2 is: " + scheduledES_count2);
scheduledES_count2 ++;
if (scheduledES_count2 > MAX_TIME)
{
isFinish.getAndSet(true);
done.countDown();
System.out.println("Scheduled thread: end success");
}
}
}
}, 0, TRY_SEND_DATA_PERIOD, UNIT);
System.out.println("Watch countDownLatch thread start");
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
// 等待上報資料成功
done.await();
System.out.println("Watch countDownLatch thread: try shutdown scheduled executor");
// 安全關閉線程池
exec.shutdown();
// 逾時退出
exec.awaitTermination(TIMEOUT, UNIT);
System.out.println("Watch countDownLatch thread: end shutdown scheduled executor");
}
catch (InterruptedException e)
{
System.out.println("Watch countDownLatch thread is interrupted, exception is: "
+ e);
}
}
}).start();
System.out.println("Scheduled thread and watch countDownLatch thread both start");
}
public void scheduleTaskByTimer()
{
Timer timer = new Timer();
timer.schedule(new TimerTask(){
@Override
public void run()
{
System.out.println("ScheduleTaskByTimer1: try start ... count1 is: " + timer_count1);
timer_count1++;
if (timer_count1 > 1)
{
throw new RuntimeException("current count is: " + timer_count1);
}
}
}, 0, TRY_SEND_DATA_PERIOD);
timer.schedule(new TimerTask(){
@Override
public void run()
{
System.out.println("ScheduleTaskByTimer2: try start ... count2 is: " + timer_count2);
timer_count2++;
}
}, 0, TRY_SEND_DATA_PERIOD);
}
public static void main(String args[])
{
TestScheTask test1 = new TestScheTask();
new Thread(new Runnable(){
@Override
public void run()
{
test1.scheduleTaskByScheduledES();
}
}).start();
TestScheTask test2 = new TestScheTask();
new Thread(new Runnable(){
@Override
public void run()
{
test2.scheduleTaskByTimer();
}
}).start();
}
}
輸出:
ScheduleTaskByTimer1: try start ... count1 is: 0
ScheduleTaskByTimer2: try start ... count2 is: 0
ScheduleTaskByScheduledES: try start ... count1 is: 0
Watch countDownLatch thread start
ScheduleTaskByScheduledES: try start ... count2 is: 0
Scheduled thread and watch countDownLatch thread both start
ScheduleTaskByTimer2: try start ... count2 is: 1
ScheduleTaskByTimer1: try start ... count1 is: 1
Exception in thread "Timer-0" ScheduleTaskByScheduledES: try start ... count1 is: 1 ------異常捕獲
ScheduleTaskByScheduledES: try start ... count2 is: 1
java.lang.RuntimeException: current count is: 2 -------異常抛出 線程終止 導緻Timer cannel
at com.csdn.test.timer.TestScheTask$4.run(TestScheTask.java:138)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
ScheduleTaskByScheduledES: try start ... count2 is: 2 ------另一線程繼續執行
ScheduleTaskByScheduledES: try start ... count2 is: 3
ScheduleTaskByScheduledES: try start ... count2 is: 4
ScheduleTaskByScheduledES: try start ... count2 is: 5
Scheduled thread: end success
Watch countDownLatch thread: try shutdown scheduled executor
Watch countDownLatch thread: end shutdown scheduled executor
---------- Timer的另一TimerTask不再執行
結果分析:
1、同一Timer對象不适合啟動多個TimerTask任務,一是因為單線程執行這些任務,二是因為任何一個TimerTask抛出未受檢異常,Timer不會進行捕獲,會導緻Timer cannel,後續任務無法繼續進行。
2、延遲或定時任務推薦使用 ScheduledExecutorService 對象的 scheduleAtFixedRate 方法,安全高效。
參考書籍:
《Java并發程式設計實戰》