2022-12-04

在使用ScheduledExecutorService進(jìn)行周期性任務(wù)執(zhí)行時(shí),遇到一個(gè)問題:

  1. 如果Runnable#run()方法拋異常的話,該異常會(huì)被ScheduledExecutorService吞掉,同時(shí)ScheduledExecutorService的周期性任務(wù)會(huì)被停掉。(如果ScheduledExecutorService有多個(gè)周期性任務(wù)的話,只有這個(gè)scheduleAtFixedRate()會(huì)被停掉,其它的可以正常執(zhí)行)。
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Demo {
    private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(3);
    private final Runnable runnable2 = () -> System.out.printf(Locale.CHINA, "[%s][%s]Runnable2 running...\n", new Date(), Thread.currentThread().getName());

    public static void main(String[] args) {
        Demo d = new Demo();
        d.test();
    }

    public void test() {
        executorService.scheduleAtFixedRate(this::executeRunnable1, 0, 1000, TimeUnit.MILLISECONDS);
        executorService.scheduleAtFixedRate(runnable2, 0, 2000, TimeUnit.MILLISECONDS);
    }

    private void executeRunnable1() {
        System.out.printf(Locale.CHINA, "[%s][%s]Runnable1 running...\n", new Date(), Thread.currentThread().getName());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            throw new RuntimeException("My Exception");
        } catch (Throwable t) { // Catch Throwable rather than Exception (a subclass).
            System.err.println(String.format(Locale.CHINA, "[%s][%s]%s\n", new Date(), Thread.currentThread().getName(), e));
        }
    }
}

Solution1:

最簡單的Solution是在Runnable#run()方法中添加try-catch。

Solution2:
public void test() {
        ScheduledFuture<?> scheduledFuture1 = executorService.scheduleAtFixedRate(this::executeRunnable1, 0, 1000, TimeUnit.MILLISECONDS);
        try {
            //可以捕捉到j(luò)ava.lang.RuntimeException: My Exception錯(cuò)誤,但是Runnable1不會(huì)持續(xù)執(zhí)行。
            scheduledFuture1.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        executorService.scheduleAtFixedRate(runnable2, 0, 2000, TimeUnit.MILLISECONDS);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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