Skip to content

java线程池、包括线程的异常处理

对于线程池、包括线程的异常处理推荐一下方式:

1 直接 try/catch,个人 基本都是用这种方式

2 线程直接重写整个方法:

java
       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;
        });

3 也可以直接重写 protected void afterExecute(Runnable r, Throwable t) { }方法

最近更新