之前总结过线程及线程池相关的文章,线程池创建也有多种方式,每种创建线程的方式又各有所异。这次总结子线程中异常的捕捉。
场景
在实际开发中,可能一些业务场景是需要开多条线程执行的,在执行过程中如果出现异常,是否能得到我们所期望的结果是和线程的执行方式有很大关系的。
代码演示
1.为做测试,此处自定义一个线程类:
public class ThreadExceptionRunner implements Runnable {
public void run() {
//子线程中直接抛空指针异常
throw new RuntimeException("I'm a Exception...");
}
}
2.测试Demo 类:
public class ThreadExceptionDemo {
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10,0L, TimeUnit.MINUTES, new LinkedBlockingQueue());
// 此处使用的submit
executor.submit(new ThreadExceptionRunner());
System.out.println("main finished...");
executor.shutdown();
}
}
3.输出结果为:(相安无事),没有报错。
4.将上面的executor.submit(new ThreadExceptionRunner());
替换为:executor.execute(new ThreadExceptionRunner());
5.输出结果:异常(这是我们所期望的结果)
6.分析原因
根据以上的自定义线程类,ThreadExceptionRunner
得知,run()
中就是抛异常,所以我们期望的线程在执行时也是抛出异常。查看第一种写法:AbstractExecutorService.submit(Runnable task)
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
//此处将task封装成了一个RunnableFuture
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
再来查看第二种写法:AbstractExecutorService.execute(Runnable command)
public void execute(Runnable command) {
// 此处省略源码
}
第一种写法是封装为RunnableFuture
。原因就在这个RunnableFuture
,由于FutureTask<V> implements RunnableFuture
,因此此处是创建了一个FutureTask
,查看FutureTask.run()
将异常设置到了outcome
对象中:
查看FutureTask.get()
和 FutureTask.report()
:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
private V report(int s) throws ExecutionException {
// 将异常信息赋值给了x
Object x = outcome;
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
由以上的代码可以得知,我们如果坚持使用submit()
的方式,则需要再调用get()
才能获取异常并抛出:
public class ThreadExceptionDemo {
public static void main(String[] args) {
ThreadPoolExecutor executorService = new ThreadPoolExecutor(5, 10,0L, TimeUnit.MINUTES, new LinkedBlockingQueue());
Future<?> submitTask = executorService.submit(new ThreadExceptionRunner());
try {
submitTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
结果如图:
控制台输出异常:
java.util.concurrent.ExecutionException: java.lang.RuntimeException: I'm a Exception...
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at cn.ibicd.design.mode.factory.test.ThreadExceptionDemo.main(ThreadExceptionDemo.java:15)
Caused by: java.lang.RuntimeException: I'm a Exception...
at cn.ibicd.design.mode.factory.test.ThreadExceptionRunner.run(ThreadExceptionRunner.java:9)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
at java.util.concurrent.FutureTask.run(FutureTask.java)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
- 上面提供了一种在主线程中捕捉子线程抛出异常的方式,我们还可以在子线程中做统一处理:于是优化上面的写法:
public class ThreadExceptionDemo {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool(new CustomThreadFactory());
executorService.execute(new ThreadExceptionRunner());
executorService.shutdown();
}
}
/**
* 自定义线程工厂
*/
class CustomThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());
return thread;
}
}
/**
* 自定义线程异常捕获Handler
*/
class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
//TODO 处理异常
System.out.println(e);
}
}