問題:ScheduledExecutorService接口是什么

問題

ScheduledExecutorService接口是什么

答案

ScheduledExecutorService接口

  • schedule方法

ScheduledExecutorService用于延遲一段時間后執(zhí)行任務(wù)或者周期性的執(zhí)行任務(wù).通常使用Executor類的工廠方法去實例化一個ScheduledExecutorService是一個比較好的方式.

這里我們創(chuàng)建一個帶有一個線程的ScheduledExecutorService.

ScheduledExecutorService executorService =Executors.newSingleThreadScheduledExecutor();

為了延遲一段時間后執(zhí)行任務(wù),使用ScheduledExecutorService接口的scheduled()方法,這個接口提供了兩個方法,用于執(zhí)行Runnable任務(wù)或者Callable任務(wù).

       Callable<String> callableTask = () -> {
            System.out.println("callAble");
            return "callAble";
        };

        Runnable runnableTask = () -> {
            System.out.println("runnable");
        };

        ScheduledExecutorService  executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.schedule(callableTask,3,TimeUnit.SECONDS);

        executorService.schedule(runnableTask,3,TimeUnit.SECONDS);

上面的代碼延遲了3秒后再執(zhí)行任務(wù).

  • scheduleAtFixedRate方法

scheduleAtFixedRate()方法在延遲一段時間之后周期性的執(zhí)行一個任務(wù).下面的代碼將會先延遲1秒之后首次執(zhí)行,之后每隔3秒執(zhí)行.如果所需要執(zhí)行的時間大于我們指定的時間,那將會在執(zhí)行時間過后立即執(zhí)行.

    ScheduledExecutorService  executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(runnableTask,1,3,TimeUnit.SECONDS);
  • scheduleWithFixedDelay方法

如果需要任務(wù)周期性執(zhí)行的時候保持固定的時間間隔,應(yīng)該使用scheduleWithFixedDalay()方法.如下的代碼保證上一次任務(wù)執(zhí)行完過10秒之后再執(zhí)行下一次任務(wù).

  executorService.scheduleWithFixedDelay(runnableTask,1,10,TimeUnit.SECONDS);

scheduleAtFixedRate()方法和scheduleWithFixedDelay()方法約定:如果ExecutorService被關(guān)閉,或者在任務(wù)執(zhí)行過程中拋出了一個異常,那么周期性執(zhí)行的任務(wù)將會終止.

最后編輯于
?著作權(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ù)。

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