java线程池对子线程异常的处理
废话不多说,直接上代码
1.通过重写线程池的afterExecute()方法,代码如下:
static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 8, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1024), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("导出线程池");
return t;
}
},new ThreadPoolExecutor.AbortPolicy()){
@Override
protected void afterExecute(Runnable r, Throwable t) {
if(null!=t){
t.printStackTrace();
}
}
};
使用线程池的execute方法提交任务
threadPoolExecutor.execute(() -> {
System.out.println(1 / 0);
});
结果如下,捕获子线程的异常
2.使用submit()提交任务,得到future对象
线程池定义如下:
static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 8, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1024), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("导出线程池");
return t;
}
},new ThreadPoolExecutor.AbortPolicy()){
};
通过submit提交任务:
try {
Future<?> future = threadPoolExecutor.submit(() -> {
System.out.println(1 / 0);
});
Object o = future.get();
}catch (Exception e){
System.out.println(e.getMessage()+" 方式二");
}
方式二结果展示:
3.实现Thread.UncaughtExceptionHandler接口
线程池定义如下:
static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 8, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1024), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("导出线程池");
//设置子线程异常的处理器
t.setUncaughtExceptionHandler(new ExportThreadPoolUncaughtExceptionHandler());
return t;
}
},new ThreadPoolExecutor.AbortPolicy()){
};
2.定义异常处理器:
static class ExportThreadPoolUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
if(null!=e){
System.out.println(e.getMessage()+" 方式三");
}
}
}
通过execute方式提交任务:
//3.实现Thread.UncaughtExceptionHandler接口,完成对子线程异常的处理
threadPoolExecutor.execute(() -> {
System.out.println(1 / 0);
});
结果展示:
以上就是通过线程池提交任务,对子线程提交任务,异常的处理,如有错误,欢迎指正。。。