thread异常处理
@org.junit.Test
public void test(){
try{
Thread t = new Thread(() -> {
System.out.println("test thread");
System.out.println(1/0);
});
t.start();
} catch (Exception e){
System.out.println("catch exception");
}
}
可以看到没有打印出catch exception,说明没有捕获到异常,在多线程的时候,我们在线程外面是捕获不到异常的
@org.junit.Test
public void test(){
Thread t = new Thread(() -> {
try{
System.out.println("test thread");
System.out.println(1/0);
} catch (Exception e){
System.out.println("catch exception");
}
});
t.start();
}
可以看到,在线程里面可以捕获到异常。
FutureTask异常处理
class ExceptionCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("run");
throw new RuntimeException("exception throw");
}
}
@org.junit.Test
public void futureTaskTest(){
FutureTask<String> task = new FutureTask<>(new ExceptionCallable());
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler((t, e) ->
System.out.println("catch exception"+ t.getName()+ e));
thread.start();
}
可以看到并没有捕获到异常,需要在future的get()来捕获异常才可以。
try{
task.get();
} catch (Exception e){
System.out.println("catch exception"+e.getMessage());
}
ThreadPoolExcutor线程池的异常处理:
使用execute提交线程的情况
这种情况如果我们没有在线程内捕获异常那么JVM会调用
Thread的UncaughtExceptionHandler的uncaughtException方法来处理异常,这是我们可以自己写逻辑覆盖其方法
public class MyHandler implements Thread.UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("threadId = {}, threadName = {}, ex = {}"
+t.getId()+ t.getName()+ e.getMessage());
}
}
测试代码:
public static void main(String[] args){
ExecutorService es = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactoryBuilder().setUncaughtExceptionHandler(new MyHandler()).build());
es.execute(() -> {
System.out.println(1/0);
});
System.out.println("x");
es.shutdown();
}
运行结果如下,说明最终执行到了我们自定义的异常捕获方法。
使用submit提交线程的情况
submit会返回一个Future对象,我们要catct,Future的get()来捕获异常
ExecutorService es = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactoryBuilder().setUncaughtExceptionHandler(new MyHandler()).build());
Future ft = es.submit(() -> {
System.out.println(1/0);
//System.out.println("x1");
});
try{
ft.get();
} catch (Exception e){
System.out.println("catch exception = {},"+e.getMessage());
}