线程运行过程当中发生的异常,没法经过try catch方式,在外层进行捕获,例如java
try { new Thread(new Runnable() { @Override public void run() { int i = 1 / 0; } }).start(); } catch (Exception e) { System.out.println("error"); }
执行上面的代码,你会发现,error永远不会打印在你的控制台或是log中,缘由为什么,没去深究,不过我想大概是由于线程有本身独立的栈区多线程
try { Thread thread = new Thread(new Runnable() { @Override public void run() { int i = 1 / 0; } }); thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("uncaughtException"); } }); thread.start(); } catch (Exception e) { System.out.println("error"); }
private static ThreadPoolExecutor executorPool = new ThreadPoolExecutor(4, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1), new SimpleThreadFactory("executor"), new CustomRejectedExecutionHandler() ) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if (t == null && r instanceof Future<?>) { try { Object result = ((Future<?>) r).get(); } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // ignore/reset } } if (t != null) { System.out.println("t is :" + t); t.printStackTrace(); } } };
这样就能够在异常发生时,能够打印出异常信息,而不是被吃掉ide
咱们在sumbit任务到ThreadPool时,自动为咱们包装成了FutureTask,而FutureTask对象在执行时,是会把异常吃掉,直到咱们get FutureTask的执行结果时才会把异常抛出。相关的代码以下: 工具