ScheduledThreadPoolExecutor線程池

1. ScheduledThreadPoolExecutor線程池
2. SpringBoot2.X整合定時線程池(ScheduledThreadPoolExecutor)

image.png

1. 線程池的構(gòu)造方法

ScheduledThreadPoolExecutor最全構(gòu)造方法:

    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       ThreadFactory threadFactory,
                                       RejectedExecutionHandler handler) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue(), threadFactory, handler);
    }

我們自定義ScheduledThreadPoolExecutor線程池的時候,可以設(shè)置核心線程數(shù)、線程工廠、拒絕策略

阻塞隊列默認使用的是DelayedWorkQueue(延遲隊列,是一個優(yōu)先級隊列,本質(zhì)上就是堆)。保證每次出隊時一定是當(dāng)前隊列中執(zhí)行時間最靠前的。

使用Executors靜態(tài)類快速創(chuàng)建ScheduledThreadPoolExecutor:

 Executors.newScheduledThreadPool(3);

2. 添加延時任務(wù)

因為ScheduledThreadPoolExecutor實現(xiàn)了ExecutorService接口,那么他也能夠使用通用的executor或者submit提交任務(wù),最終調(diào)用schedule方法,默認馬上執(zhí)行一次。若需要延遲執(zhí)行,可直接使用schedule方法,傳遞時間參數(shù)。

//延遲delay時間后,執(zhí)行任務(wù)。因為傳入的是Runnable,故get()方法獲取的為null
public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);
 //帶返回值的延遲任務(wù)
 public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit);

3. 添加周期任務(wù)

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);
  • scheduleAtFixedRate:按照固定的頻率執(zhí)行,不受執(zhí)行時長影響,若發(fā)生misfire(即上一次執(zhí)行時長大于period),則下一次任務(wù)立即執(zhí)行。
  • scheduleWithFixedDelay:任務(wù)執(zhí)行完畢后,按照固定的delay時間間隔執(zhí)行。

4. 如何終止周期任務(wù)

方式一:拋出異常,即可終止定時任務(wù)。

        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
        scheduledExecutorService.scheduleWithFixedDelay(() -> {
            System.out.println("start scheduled...");
            throw new RuntimeException();
        }, 0, 1000, TimeUnit.MILLISECONDS);

方式二:調(diào)用Future的cancal方法

future.cancel(false);

文章參考

線程池之ScheduledThreadPoolExecutor

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容