线程池提交分为 execute
与 submit
,而且 submit
是有返回值的,需要 futureTask.get();
这样获取异常信息,想要全局同时处理 execute
与 submit
线程池异常的话,只有自定义线程池,如:
package com.example.demo;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* author xiaochi
* date 2023/3/31
*/
public class TheadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
/*ExecutorService executorService = Executors.newFixedThreadPool(1);
System.out.println(executorService.submit(new Task()).get());*/
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(10)) {
/**
* 全局处理线程池异常 execute 与 submit
* @param r
* @param t
*/
@Override
protected void afterExecute(Runnable r, Throwable t) {
if (t != null) {
System.out.println("异常信息:" + t);
}
// 如果是 submit提交,出现异常会走这里
//如果r的实际类型是FutureTask 那么是submit提交的,所以可以在里面get到异常
if (r instanceof FutureTask){
FutureTask<?> futureTask = (FutureTask<?>) r;
try {
futureTask.get();
} catch (Exception e) {
e.printStackTrace();
System.out.println("线程池submit提交,异常处理:"+e);
}
}
}
};
threadPoolExecutor.submit(new Task());
threadPoolExecutor.shutdown();
}
}
class Task implements Runnable{
@Override
public void run() {
System.out.println("进来了");
int i = 1 / 0;
}
}
如此使用全局自定义的线程池就ok了。