ScheduledThreadPoolExecutor是ThreadPoolExecutor的子類;
JDK api裏是這麼說的:
ThreadPoolExecutor
,它可另行安排在給定的延遲後運行命令,或者定期執行命令。需要多個輔助線程時,或者要求 ThreadPoolExecutor
具有額外的靈活性或功能時,此類要優於 Timer
。
一旦啓用已延遲的任務就執行它,但是有關何時啓用,啓用後何時執行則沒有任何實時保證。按照提交的先進先出 (FIFO) 順序來啓用那些被安排在同一執行時間的任務。
---------------
平時我們在執行一個定時任務時,會採用Time,和TimeTask來組合處理;
但是Timer和TimerTask存在一些缺陷:
1:Timer只創建了一個線程。當你的任務執行的時間超過設置的延時時間將會產生一些問題。
2:Timer創建的線程沒有處理異常,因此一旦拋出非受檢異常,該線程會立即終止。
JDK 5.0以後推薦使用ScheduledThreadPoolExecutor。該類屬於Executor Framework,它除了能處理異常外,還可以創建多個線程解決上面的問題。
以下爲測試代碼:
[java] view plain copy
public class TaskTest {
static ScheduledThreadPoolExecutor stpe = null;
static int index;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//構造一個ScheduledThreadPoolExecutor對象,並且設置它的容量爲5個
stpe = new ScheduledThreadPoolExecutor(5);
MyTask task = new MyTask();
//隔2秒後開始執行任務,並且在上一次任務開始後隔一秒再執行一次;
// stpe.scheduleWithFixedDelay(task, 2, 1, TimeUnit.SECONDS);
//隔6秒後執行一次,但只會執行一次。
stpe.schedule(task, 6, TimeUnit.SECONDS);
}
private static String getTimes() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
Date date = new Date();
date.setTime(System.currentTimeMillis());
return format.format(date);
}
private static class MyTask implements Runnable {
@Override
public void run() {
index++;
System.out.println("2= " + getTimes()+" " +index);
if(index >=10){
stpe.shutdown();
if(stpe.isShutdown()){
System.out.println("停止了????");
}
}
}
}
}