先說scheduleWithFixedDelay(),
scheduleWithFixedDelay從字面意義上可以理解爲就是以固定延遲(時間)來執行線程任務,它實際上是不管線程任務的執行時間的,每次都要把任務執行完成後再延遲固定時間後再執行下一次。
而scheduleFixedRate呢,是以固定頻率來執行線程任務,固定頻率的含義就是可能設定的固定時間不足以完成線程任務,但是它不管,達到設定的延遲時間了就要執行下一次了。
不知道大家理解了沒有,下面是示例:
public static void scheduleWithFixedDelay() {
final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
// 響鈴線程
final Runnable beeper = new Runnable() {
public void run() {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long time = (long) (Math.random() * 1000);
// 輸出線程的名字和使用目標對象及休眠的時間
System.out.println(sf.format(new Date())+"線程:"+Thread.currentThread().getName()+":Sleeping"+time+"ms");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
};
// 設定執行線程計劃,初始10s延遲,每次任務完成後延遲10s再執行一次任務
final ScheduledFuture<?> sFuture=scheduledExecutorService.scheduleWithFixedDelay(beeper,10,10,TimeUnit.SECONDS);
// 40s後取消線程任務
scheduledExecutorService.schedule(new Runnable() {
public void run() {
sFuture.cancel(true);
scheduledExecutorService.shutdown();
}
}, 40, TimeUnit.SECONDS);
}
執行結果:
2013-10-16 10:45:51 線程:pool-1-thread-2:Sleeping 726ms
2013-10-16 10:46:02 線程:pool-1-thread-2:Sleeping 288ms
2013-10-16 10:46:12 線程:pool-1-thread-2:Sleeping 294ms
從執行結果數量看只執行了3次,因爲每次要把任務執行完成再執行下一次,導致40s按10s的延遲時間不足以執行4次。
public static void scheduleAtFixedRate() {
// 聲明線程池
final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
// 響鈴線程
final Runnable beeper = new Runnable() {
public void run() {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long time = (long) (Math.random() * 1000);
// 輸出線程的名字和使用目標對象及休眠的時間
System.out.println(sf.format(new Date()) + " 線程:" + Thread.currentThread().getName() + ":Sleeping " + time + "ms");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
};
// 計劃響鈴,初始延遲10s然後以10s的頻率執行響鈴
final ScheduledFuture<?> beeperHandle = scheduledExecutorService.scheduleAtFixedRate(beeper, 10, 10, TimeUnit.SECONDS);
// 取消響鈴並關閉線程
final Runnable cancelBeeper = new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + "CANCEL...");
beeperHandle.cancel(true);
scheduledExecutorService.shutdown();
}
};
// 60s後執行scheduleAtFixedRate
scheduledExecutorService.schedule(cancelBeeper, 40, TimeUnit.SECONDS);
}
執行結果:
2013-10-16 10:16:50 線程:pool-1-thread-1:Sleeping 868ms
2013-10-16 10:17:00 線程:pool-1-thread-1:Sleeping 587ms
2013-10-16 10:17:10 線程:pool-1-thread-1:Sleeping 313ms
2013-10-16 10:17:20 線程:pool-1-thread-1:Sleeping 969ms
pool-1-thread-1CANCEL...
看時間我們就可以知道是每個10s就執行下一次了。