ScheduledExecutorService異常分析

一、源碼解析

關(guān)注一塊代碼:

/**
     * Creates and executes a periodic action that becomes enabled first
     * after the given initial delay, and subsequently with the given
     * period; that is executions will commence after
     * {@code initialDelay} then {@code initialDelay+period}, then
     * {@code initialDelay + 2 * period}, and so on.
     * If any execution of the task
     * encounters an exception, subsequent executions are suppressed.
     * Otherwise, the task will only terminate via cancellation or
     * termination of the executor.  If any execution of this task
     * takes longer than its period, then subsequent executions
     * may start late, but will not concurrently execute.
     *
     * @param command the task to execute
     * @param initialDelay the time to delay first execution
     * @param period the period between successive executions
     * @param unit the time unit of the initialDelay and period parameters
     * @return a ScheduledFuture representing pending completion of
     *         the task, and whose {@code get()} method will throw an
     *         exception upon cancellation
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if command is null
     * @throws IllegalArgumentException if period less than or equal to zero
     */
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);

二寒亥、說明

由scheduleAtFixedRate產(chǎn)生的周期工作線程洒忧,如果遇到任何意外則會停止后續(xù)執(zhí)行;
如果執(zhí)行的Runnable線程任務(wù)沒有加異常烤惊,則會出現(xiàn)只執(zhí)行一次則線程停止的問題乔煞!特別引起重視!

三柒室、總結(jié)

1渡贾、獲取一個(gè)線程池定時(shí)任務(wù)異常關(guān)閉的小tip,注意任何心跳類希望一直保持線程定時(shí)任務(wù)雄右,為保證線程可靠性空骚,最好捕獲異常進(jìn)行相關(guān)保護(hù)纺讲;
2、靈感源于代碼囤屹,因此切忌遇到問題要關(guān)注代碼底層實(shí)現(xiàn)熬甚,學(xué)會看jdk文檔接口的詳細(xì)說明,可以少走很多彎路肋坚;
3乡括、學(xué)習(xí)ScheduledFuture這個(gè)返回:

  • 繼承了Delayed, Future<V>兩個(gè)接口
  • long getDelay(TimeUnit unit);支持返回線程任務(wù)的最近間隔時(shí)間
  • future提供的cancel、get等方法用于任務(wù)取消或者獲取智厌,作用也很重要诲泌,注意學(xué)習(xí)用法

四、測試代碼

package FutureScheuledTest;

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

/**
 * Created by fwding on 2018/3/21 0021.
 */
public class FutureScheduledTest {
    private static ScheduledFuture global_sfd;
    public static void main(String[] args) throws Exception {
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(10);
        ScheduledFuture sfa = ses.scheduleAtFixedRate(new TimerTask("a"), 200,
                1000, TimeUnit.MILLISECONDS);
        ScheduledFuture sfb = ses.scheduleAtFixedRate(new TimerTask("b"), 400,
                1000, TimeUnit.MILLISECONDS);
        ScheduledFuture sfc = ses.scheduleAtFixedRate(new TimerTask("c"), 600,
                1000, TimeUnit.MILLISECONDS);
        global_sfd = ses.scheduleAtFixedRate(new TimerTask("d"), 800,
                1000, TimeUnit.MILLISECONDS);
        Thread.sleep(5000);
        sfa.cancel(true);
        sfb.cancel(true);
        sfc.cancel(true);
        global_sfd.cancel(true);

        Thread.sleep(5000);
        ses.shutdown();
    }

    static class TimerTask implements Runnable{
        private String id;
        public TimerTask(String id){
            this.id = id;
        }
        @Override
        public void run(){
            System.out.println(id);
            //
            System.out.println("ID:" + id +"------------THREAD_D:TIME DELAY:" +
                    global_sfd.getDelay(TimeUnit.MILLISECONDS));
            if (!id.equals("d") && global_sfd.getDelay(TimeUnit.MILLISECONDS) < 400) {
                global_sfd.cancel(true);
                System.out.println("ID:" + id +"------------stop the THREAD_D!!!!!!");
                Thread.currentThread().stop();
            }

            //異常測試
            /*
            try {
                int[] s = new int[2];
                s[0] = 1;
                s[1] = 2;
                s[2] = 3;
            } catch (Exception e) {
                e.printStackTrace();
            }
            */
        }
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末峦剔,一起剝皮案震驚了整個(gè)濱河市档礁,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌吝沫,老刑警劉巖呻澜,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異惨险,居然都是意外死亡羹幸,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進(jìn)店門辫愉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來栅受,“玉大人,你說我怎么就攤上這事恭朗∑聊鳎” “怎么了?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵痰腮,是天一觀的道長而芥。 經(jīng)常有香客問我,道長膀值,這世上最難降的妖魔是什么棍丐? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮沧踏,結(jié)果婚禮上歌逢,老公的妹妹穿的比我還像新娘。我一直安慰自己翘狱,他們只是感情好秘案,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般踏烙。 火紅的嫁衣襯著肌膚如雪师骗。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天讨惩,我揣著相機(jī)與錄音,去河邊找鬼寒屯。 笑死荐捻,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的寡夹。 我是一名探鬼主播处面,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼菩掏!你這毒婦竟也來了魂角?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤智绸,失蹤者是張志新(化名)和其女友劉穎野揪,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體瞧栗,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡斯稳,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了迹恐。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片挣惰。...
    茶點(diǎn)故事閱讀 40,503評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖殴边,靈堂內(nèi)的尸體忽然破棺而出憎茂,到底是詐尸還是另有隱情,我是刑警寧澤锤岸,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布竖幔,位于F島的核電站,受9級特大地震影響能耻,放射性物質(zhì)發(fā)生泄漏赏枚。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一晓猛、第九天 我趴在偏房一處隱蔽的房頂上張望饿幅。 院中可真熱鬧,春花似錦戒职、人聲如沸栗恩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽磕秤。三九已至乳乌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間市咆,已是汗流浹背汉操。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蒙兰,地道東北人磷瘤。 一個(gè)月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像搜变,于是被迫代替她去往敵國和親采缚。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容