一個Java細節!

本文首發於我的微信公衆號《andyqian》,期待你的關注!

前言

  今天咱們一塊兒來作個簡單有趣的實驗。熟悉Java的童鞋,對ScheduledExecutorService 類應該不陌生。不記得的童鞋,先回憶下。微信

實驗一

咱們先看下下面這段簡單的代碼。以下:ide

public class ExecutoryServiceTest {

        private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);

        public static void main(String[] args){
            executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                        int[] array  = new int[1];
                        System.out.println("<hello world>");
                        System.out.println(array[1]);
                }},0,2, TimeUnit.SECONDS);
            }
        }

夠簡單了吧。意思我就再也不闡述了。看完別急,咱們先回答下面這個問題。函數

問題一:

請問:上面一共打印了多少個<hello world>spa

實驗二

  看到此處的童鞋,請在評論區給出你第一個實驗的答案。緊接着,咱們繼續看第二個實驗。
.net

public class ExecutoryServiceTest {

        private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);

        public static void main(String[] args){
            executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    try {
                        int[] array = new int[1];
                        System.out.println("<hello world>");
                        System.out.println(array[1]);
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                }},0,2, TimeUnit.SECONDS);
            }
        }

問題二:

請問: 實驗二中一共打印了多少個<hello world>。code

請在評論區中給出你的答案。blog

分析

  通過上述兩個實驗後,咱們會發現二者的答案並不相同。這是爲何呢?由於在:run()方法中,發生異常後,中斷了後續的執行。這是爲何呢?圖片

其實呀,早在:scheduleAtFixedRate()JDK源碼中就有這麼一段描述:get

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.源碼

其意思就是告訴咱們:若是任何執行任務遇到異常,其後續的操做會被壓制。

一樣的,在scheduleWithFixedDelay()方法中也有一樣的描述。

一點點建議

  1. 在使用scheduleAtFixedRate()scheduleWithFixedDelay()時,run()方法均要在使用try{}catch處理。避免出現定時任務執行若干次後不執行的」怪現象」。

  2. 咱們平時在寫系統時,不管是使用JDK自帶函數,仍是對接外部服務。使用時,必定要了解其使用方法。對入參,結果等都充分理解。(不瞞你說,我就出現過不少次沒理解充分。致使Bug產生)。

  3. 強烈建議你們都在本機上運行下上面這兩段實驗的代碼。這樣有利於加深印象。

最後: 你們晚安

這裏寫圖片描述

 掃碼關注,一塊兒進步

我的博客: http://www.andyqian.com

相關文章
相關標籤/搜索