多線程編程中,run
方法中的代碼一定要用try...catch
包裹,否則會出現如下問題
-
run
方法中使用while
循環,沒有try
和try
在while
外面是等價的,當run
方法中出現異常,會導致while
循環結束// 錯誤示例: @Override public void run() { while (true) { System.out.println("run"); } } // 錯誤示例: @Override public void run() { try { while (true) { System.out.println("run"); } } catch (Exception e) { System.out.println("error"); } } // 正確示例: @Override public void run() { while (true) { try { String key = queue.take(); DistinctRequest<?> request = (DistinctRequest<?>) localCacheService.getIfPresent(key); if (null != request) { LOGGER.info("處理請求:{}", request.getRouteId()); // 此處可能丟失最新的消息 localCacheService.invalidate(key); request.process(); } else { LOGGER.info("key:{} 請求已處理或請求已失效...", key); } } catch (Exception e) { LOGGER.error("RequestProcessorThread:{}", e.toString()); } } }
-
使用
ScheduledThreadPoolExecutor
執行週期任務時,Runnable
的run
方法中沒有try
代碼塊,出現異常時會導致任務不再執行。如使用下面的方法創建週期任務ScheduledThreadPoolExecutor#scheduleWithFixedDelay