9、java5線程池之定時任務線程池newScheduledThreadPool與newSingleThreadScheduledExecutor


JDK文檔描述

newSingleThreadScheduledExecutor()

創建一個單線程執行程序,它可安排在給定延遲后運行命令或者定期地執行。(注意,如果因為在關閉前的執行期間出現失敗而終止了此單個線程,那么如果需要,一個新線程會代替它執行后續的任務)。可保證順序地執行各個任務,並且在任意給定的時間不會有多個線程是活動的。與其他等效的 newScheduledThreadPool(1) 不同,可保證無需重新配置此方法所返回的執行程序即可使用其他的線程。
newScheduledThreadPool()

創建一個線程池,它可安排在給定延遲后運行命令或者定期地執行。 

 

通過上面2個方法返回的對象為:ScheduledExecutorService

public interface ScheduledExecutorService extends ExecutorService
  一個 ExecutorService,可安排在給定的延遲后運行或定期執行的命令。 schedule 方法使用各種延遲創建任務,並返回一個可用於取消或檢查執行的任務對象。scheduleAtFixedRate 和 scheduleWithFixedDelay 方法創建並執行某些在取消前一直定期運行的任務。 用 Executor.execute(java.lang.Runnable) 和 ExecutorService 的 submit 方法所提交的命令,通過所請求的
0 延遲進行安排。schedule 方法中允許出現 0 和負數延遲(但不是周期),並將這些視為一種立即執行的請求。 所有的 schedule 方法都接受相對 延遲和周期作為參數,而不是絕對的時間或日期。將以 Date 所表示的絕對時間轉換成要求的形式很容易。例如,要安排在某個以后的 Date 運行,可以使用:schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)。但是要注意,由於網絡時間同步協議、時鍾漂移或其他因素的存在,因此相對延遲的期滿日期不必與啟用任務的當前 Date 相符。 Executors 類為此包中所提供的 ScheduledExecutorService 實現提供了便捷的工廠方法。

 

以下為JDK自帶的例子:

以下是一個帶方法的類,它設置了 ScheduledExecutorService ,在 1 小時內每 10 秒鍾蜂鳴一次:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class BeeperControl {
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
            public void run() {
                System.out.println("beep");
            }
        };
        final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, TimeUnit.SECONDS);
        scheduler.schedule(new Runnable() {
            public void run() {
                beeperHandle.cancel(true);
            }
        }, 60 * 60, TimeUnit.SECONDS);
    }
}

 

ScheduledExecutorService類的主要方法:

方法摘要
<V> ScheduledFuture<V>

schedule(Callable<V> callable, long delay, TimeUnit unit)
創建並執行在給定延遲后啟用的 ScheduledFuture。

 ScheduledFuture<?>

schedule(Runnable command, long delay, TimeUnit unit)
創建並執行在給定延遲后啟用的一次性操作。

ScheduledFuture<?>

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
創建並執行一個在給定初始延遲后首次啟用的定期操作,后續操作具有給定的周期;也就是將在 initialDelay 后開始執行,然后在 initialDelay+period 后執行,接着在 initialDelay + 2 * period 后執行,依此類推。

ScheduledFuture<?>

scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
創建並執行一個在給定初始延遲后首次啟用的定期操作,隨后,在每一次執行終止和下一次執行開始之間都存在給定的延遲。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM