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.創(chuàng)建線程
???????//1.手動創(chuàng)建
???????Thread student = new Thread();
???????student.setUncaughtExceptionHandler(new UncaughtExceptionHandlerMy());
???????student.start();
???????//2.ExecutorService創(chuàng)建
? ??????ExecutorService executorService =Executors.newFixedThreadPool(3, new ThreadFactoryMy());
???????//3 ThreadPoolTaskExecutor創(chuàng)建
???????ThreadPoolTaskExecutor threadPoolTaskExecutor = newThreadPoolTaskExecutor();
???????threadPoolTaskExecutor.setThreadFactory(new ThreadFactoryMy());
3.但是上述只會在子線程中抓住并打印,若需要主線得到子線程的異常,并開展業(yè)務,則
實現callabel,用future返回線程執(zhí)行結果
??static class Teacher implements Callable {
???????@Override
???????public Object call() throws Exception {
???????????int i = 1 / 0;
???????????System.out.println("執(zhí)行");
???????????return null;
???????}
}
主線程
try {
???????????Future submit = executorService.submit(new Teacher());
???????????Object o = submit.get();
???????} catch (Exception e) {
???????????System.out.println("抓住子線程異常");
???????????throw new RuntimeException("自定義異常");
???????}