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);
});
結果展示:
以上就是通過線程池提交任務,對子線程提交任務,異常的處理,如有錯誤,歡迎指正。。。