submit 与 execute

注: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抛出的异常。


  1. for (Future<String> fs : resultList) {  
  2.             try {  
  3.                 System.out.println(fs.get()); // 打印各个线程(任务)执行的结果  
  4.             } catch (InterruptedException e) {  
  5.                 e.printStackTrace();  
  6.             } catch (ExecutionException e) {  
  7.                 executorService.shutdownNow();  
  8.                 e.printStackTrace();  
  9.                 return;  
  10.             }  
  11.         }
原始exception抛出处:

  1. if (new Random().nextBoolean())  
  2.             throw new TaskException("Meet error in task." + Thread.currentThread().getName());
最终:

  1. java.util.concurrent.ExecutionException: com.cicc.pts.TaskException: Meet error in task.pool-1-thread-3  
  2.     at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)  
  3.     at java.util.conc


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值