解析Java線程池的異常處理機制

參考:https://segmentfault.com/a/1190000010777336

submit的方式會吃掉異常,execute的方式會直接拋出

之後定義的時候要這樣定義

對於線程池、包括線程的異常處理推薦一下方式:

  1. 直接try/catch,個人 基本都是用這種方式

  2. 線程直接重寫整個方法:

           Thread t = new Thread();
           t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
     
    public void uncaughtException(Thread t, Throwable e) {
    LOGGER.error(t + " throws exception: " + e);
    }
            });
            //如果是線程池的模式:
            ExecutorService threadPool = Executors.newFixedThreadPool(1, r -> {
     Thread t = new Thread(r);
     t.setUncaughtExceptionHandler(
      (t1, e) -> LOGGER.error(t1 + " throws exception: " + e));
     return t;
            });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章