溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java調(diào)度線程池ScheduledThreadPoolExecutor不執(zhí)行問題怎么解決

發(fā)布時間:2023-03-02 11:54:38 來源:億速云 閱讀:94 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Java調(diào)度線程池ScheduledThreadPoolExecutor不執(zhí)行問題怎么解決”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“Java調(diào)度線程池ScheduledThreadPoolExecutor不執(zhí)行問題怎么解決”吧!

    ScheduledThreadPoolExecutor不調(diào)度分析

    示例程序

    在示例程序可以看到當(dāng)計數(shù)器中的計數(shù)達到5的時候就會主動拋出一個異常,拋出異常后ScheduledThreadPoolExecutor就不調(diào)度了。

    public class ScheduledTask {
        private static final AtomicInteger count = new AtomicInteger(0);
        private static final ScheduledThreadPoolExecutor SCHEDULED_TASK = new ScheduledThreadPoolExecutor(
                1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(Thread.currentThread().getThreadGroup(), r, "sc-task");
                t.setDaemon(true);
                return t;
            }
        });
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch latch = new CountDownLatch(1);
            SCHEDULED_TASK.scheduleWithFixedDelay(() -> {
                System.out.println(111);
                if (count.get() == 5) {
                    throw new IllegalArgumentException("my exception");
                }
                count.incrementAndGet();
            }, 0, 5, TimeUnit.SECONDS);
            latch.await();
        }
    }

    源碼分析

    ScheduledThreadPoolExecutor#run

    run方法內(nèi)部首先判斷任務(wù)是不是周期性的任務(wù),如果不是周期性任務(wù)通過ScheduledFutureTask.super.run();執(zhí)行任務(wù);如果狀態(tài)是運行中或shutdown,取消任務(wù)執(zhí)行;如果是周期性的任務(wù),通過ScheduledFutureTask.super.runAndReset()執(zhí)行任務(wù)并且重新設(shè)置狀態(tài),成功了就會執(zhí)行setNextRunTime設(shè)置下次調(diào)度的時間,問題就是出現(xiàn)在ScheduledFutureTask.super.runAndReset(),這里執(zhí)行任務(wù)出現(xiàn)了異常,導(dǎo)致結(jié)果為false,就不進行下次調(diào)度時間設(shè)置等

            public void run() {
                boolean periodic = isPeriodic();
                if (!canRunInCurrentRunState(periodic))
                    cancel(false);
                else if (!periodic)
                    ScheduledFutureTask.super.run();
                else if (ScheduledFutureTask.super.runAndReset()) {
                    setNextRunTime();
                    reExecutePeriodic(outerTask);
                }
            }

    *FutureTask#runAndReset

    在線程任務(wù)執(zhí)行過程中拋出異常,然后catch到了異常,最終導(dǎo)致這個方法返回false,然后ScheduledThreadPoolExecutor#run就不設(shè)置下次執(zhí)行時間了,代碼c.call(); 拋出異常,跳過ran = true;代碼,最終runAndReset返回false。

        protected boolean runAndReset() {
            if (state != NEW ||
                !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                             null, Thread.currentThread()))
                return false;
            boolean ran = false;
            int s = state;
            try {
                Callable<V> c = callable;
                if (c != null && s == NEW) {
                    try {
                        c.call(); // don't set result
                        ran = true;
                    } catch (Throwable ex) {
                        setException(ex);
                    }
                }
            } finally {
                // runner must be non-null until state is settled to
                // prevent concurrent calls to run()
                runner = null;
                // state must be re-read after nulling runner to prevent
                // leaked interrupts
                s = state;
                if (s >= INTERRUPTING)
                    handlePossibleCancellationInterrupt(s);
            }
            return ran && s == NEW;
        }

    到此,相信大家對“Java調(diào)度線程池ScheduledThreadPoolExecutor不執(zhí)行問題怎么解決”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI