在submit之后可以获得一个线程执行结果的Future对象,而如果子线程中发生了异常,通过future.get()获取返回值时,可以捕获到
ExecutionException异常,从而知道子线程中发生了异常。
子线程代码:
public class ChildThread implements Callable {
public Object call() throws Exception {
System.out.println("do something 1");
exceptionMethod();
System.out.println("do something 2");
return null;
}
private void exceptionMethod() {
throw new RuntimeException("ChildThread1 exception");
}
}
父线程代码:
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(8);
Future future = executorService.submit(new ChildThread());
try {
future.get();
} catch (InterruptedException e) {
System.out.println(String.format("handle exception in child thread. %s", e));
} catch (ExecutionException e) {
System.out.println(String.format("handle exception in child thread. %s", e));
} finally {
if (executorService != null) {
executorService.shutdown();
}
}
}
}
命令行输出:
do something 1
handle exception in child thread. java.util.concurrent.ExecutionException: java.lang.RuntimeException: ChildThread1 exception
总结
以上就是3种常用的Java子线程异常处理方法。其实楼主还想到了另外几个特定场景下的解决办法,改天再分析,谢谢大家支持~