今天咱們一塊兒來作個簡單有趣的實驗。熟悉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()
方法中也有一樣的描述。
在使用scheduleAtFixedRate()
或scheduleWithFixedDelay()
時,run()
方法均要在使用try{}catch
處理。避免出現定時任務執行若干次後不執行的」怪現象」。
咱們平時在寫系統時,不管是使用JDK自帶函數,仍是對接外部服務。使用時,必定要了解其使用方法。對入參,結果等都充分理解。(不瞞你說,我就出現過不少次沒理解充分。致使Bug產生)。
強烈建議你們都在本機上運行下上面這兩段實驗的代碼。這樣有利於加深印象。
最後: 你們晚安
掃碼關注,一塊兒進步
我的博客: http://www.andyqian.com