2021-08-26 java 主线程捕获子线程异常_Java子线程中的异常处理

java 主线程捕获子线程异常_Java子线程中的异常处理


正常情况下异常需要自己的线程中取catch的,在主线程是抓不住的,而子线程异常没抓住的话,就是打印在控制台不方便排查,下面介绍一些处理


1.自定义实现Thread.UncaughtExceptionHandler,并制定线程工程时生产的线程都有这个策略


static class ThreadFactoryMy implements ThreadFactory{

    @Override

    public Thread newThread(Runnable r) {

        Thread thread = new Thread(r);

        thread.setUncaughtExceptionHandler(newUncaughtExceptionHandlerMy());

        return thread;

    }

}

static class UncaughtExceptionHandlerMy implements Thread.UncaughtExceptionHandler{

    @SneakyThrows

    @Override

    public void uncaughtException(Threadt, Throwable e) {

        log.error(e.getMessage());

    }

}


2.创建线程

       //1.手动创建

       Thread student = new Thread();

       student.setUncaughtExceptionHandler(new UncaughtExceptionHandlerMy());

       student.start();

       //2.ExecutorService创建

        ExecutorService executorService =Executors.newFixedThreadPool(3, new ThreadFactoryMy());

       //3 ThreadPoolTaskExecutor创建

       ThreadPoolTaskExecutor threadPoolTaskExecutor = newThreadPoolTaskExecutor();

       threadPoolTaskExecutor.setThreadFactory(new ThreadFactoryMy());


3.但是上述只会在子线程中抓住并打印,若需要主线得到子线程的异常,并开展业务,则

实现callabel,用future返回线程执行结果




  static class Teacher implements Callable {


       @Override

       public Object call() throws Exception {

           int i = 1 / 0;

           System.out.println("执行");

           return null;

       }

}


主线程

try {

           Future submit = executorService.submit(new Teacher());

           Object o = submit.get();


       } catch (Exception e) {

           System.out.println("抓住子线程异常");

           throw new RuntimeException("自定义异常");

       }

你可能感兴趣的:(2021-08-26 java 主线程捕获子线程异常_Java子线程中的异常处理)