- 方法一:重写线程工厂,重写afterExecute 方法
- 方法二:设置一个全局异常处理器
public class MyWork {
public static void main(String[] args) {
ThreadPoolExecutor executor=
new ThreadPoolExecutor(
1,
1,
0,
TimeUnit.HOURS,
new LinkedBlockingDeque<>(3)
){
@Override
protected void afterExecute(Runnable r, Throwable t) {
System.err.printf("线程[%s] 遇到异常",Thread.currentThread().getName()
,t.getMessage());
}
};
executor.execute(
()->{
Thread.currentThread().setName("老弟线程");
throw new RuntimeException("抱歉,看你不顺眼");
}
);
try {
executor.awaitTermination(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
executor.shutdown();
}
}
}
public class MyWork {
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println(String.format("%d %s %s",System.currentTimeMillis(),t.getName(),e.toString()));
}
});
Thread tmp = new Thread(()->{
System.out.println('-');
int i = 0;
int j = 10/i;
});
tmp.setName("老弟线程");
tmp.start();
}
}