注:ThreadPoolExecutor 的 submit() 底层调用 execute()
submit方便Exception处理
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute
this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err
). If you submitted the task with submit
any thrown exception, checked or not, is then part of the task's return status. For a task that was submitted with submit
and that terminates with an exception, the Future.get
will rethrow this exception, wrapped in an ExecutionException
.
意思就是如果你在你的task里会抛出checked或者unchecked exception,而你又希望外面的调用者能够感知这些exception并做出及时的处理,那么就需要用到submit,通过捕获Future.get抛出的异常。
- for (Future<String> fs : resultList) {
- try {
- System.out.println(fs.get()); // 打印各个线程(任务)执行的结果
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- executorService.shutdownNow();
- e.printStackTrace();
- return;
- }
- }
- if (new Random().nextBoolean())
- throw new TaskException("Meet error in task." + Thread.currentThread().getName());
- java.util.concurrent.ExecutionException: com.cicc.pts.TaskException: Meet error in task.pool-1-thread-3
- at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
- at java.util.conc