submit 与 execute

本文讨论了在使用ThreadPoolExecutor的submit方法提交任务时如何处理抛出的异常,特别是当异常为checked或unchecked类型时,如何确保调用者能够接收到并处理这些异常。通过示例代码展示了如何在获取Future对象时捕获并处理这些异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注: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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值