標籤:over class scheduled oid schedule 筆記 時間 rri 不同
僅以此隨筆記錄一些在java中踩過而且又重踩的坑 _(:з)∠)_
1. Runnable In ScheduledExecutorsService
當使用ScheduledExecutorService, Runnable內沒有捕獲的RuntimeException將會使Executor停止運行,並且異常不會被輸出。
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (Math.random() > 0.5) throw new NullPointerException("THROW A NPE HERE"); System.out.println("tick"); } }, 0, 1, TimeUnit.SECONDS);
可以試著執行這段代碼,定時任務將在你不知不覺中停止。因此,在使用ScheduledExecutorService時,若需要處理不確定值的輸入(例如解析數字字串、解析時間、拆分字串等),強烈建議用try-catch捕獲異常。
不同於在普通的方法體裡,在這裡建議使用Exception來而不是特定的Exception。
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { if (Math.random() > 0.5) throw new NullPointerException("A NPE HERE"); System.out.println("tick"); } catch (Exception e) { // handle your exception here } } }, 0, 1, TimeUnit.SECONDS);
Java中那些踩過的坑