多线程之运行线程异常捕获
单个线程异常捕获
/**
* @description: 线程异常捕捉
* @author: Administrator
* @create: 2019-12-23 22:22
**/
public class ThreadException {
public static void main(String[] args) {
//线程抛出异常
//thread1();
//捕获异常
thread2();
}
static void thread1(){
Thread thread = new Thread(() -> {
try {
Thread.sleep(2_000);
int i = 10/0;
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
}
static void thread2(){
Thread thread = new Thread(() -> {
try {
Thread.sleep(2_000);
int i = 10/0;
} catch (InterruptedException e) {
e.printStackTrace();
}
});
//输出异常信息
thread.setUncaughtExceptionHandler((t, e) -> {
System.out.println(t);
System.out.println(e);
});
thread.start();
}
}
thread1()方法运行结果
捕获线程异常使用 setUncaughtExceptionHandler(Thread t,Exception e)方法捕捉异常信息返回,然后再进行处理
thread1()方法运行结果
线程池捕捉异常
public class ThreadPoolException {
public static void main(String[] args) {
//设置异常处理器
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
//线程池
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new ThreadTask());
executorService.shutdown();
}
}
异常处理器
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("捕获到异常 : 线程名[" + t.getName() + "], 异常名[" + e + "]");
// 异常栈的信息
e.printStackTrace();
// TODO ... 如果对异常还需要做特殊处理,可以在此处继续实现处理方法
}
}
自定义抛出异常的线程
class ThreadTask implements Runnable {
@Override
public void run() {
//运行异常
System.out.println(Thread.currentThread().getName());
System.out.println("异常被谁处理:" + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
异常捕获