线程的execute()和submit()区别
execute接收runnable对象参数,方法不会返回执行结果,但是submit可以接受runnable和callable对象参数,通过结果封装进futrue,futrue.get()方法获取结果和异常信息,
但是以上两种该方法都无法捕获异常信息,解决方式就是使用ThreadFactory,实现它的UncaughtExceptionHandler。
ThreadFactory factory = r->{
Thread thread = Executors.defaultThreadFactory().newThread(r);
thread.setUncaughtExceptionHandler( (t,e) -> {
System.out.println(t + "" + e);
e.printStackTrace();//example
});
return thread ;
};
ExecutorService service = Executors.newFixedThreadPool(1,factory);
Runnable r = () -> {
System.out.println("a");
System.out.println(1 / 0);
};
service.execute(r);
service.shutdown();
日志如下
a
Thread[pool-1-thread-1,5,main]java.lang.ArithmeticException: / by zero