Java多線程run方法中一定要用try...catch

多線程編程中,run方法中的代碼一定要用try...catch包裹,否則會出現如下問題

  • run方法中使用while循環,沒有trytrywhile外面是等價的,當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執行週期任務時,Runnablerun方法中沒有try代碼塊,出現異常時會導致任務不再執行。如使用下面的方法創建週期任務

    ScheduledThreadPoolExecutor#scheduleWithFixedDelay
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章