Callable抛出异常与future.get

本文介绍了一个使用Java线程池执行异步任务的例子,并演示了如何捕获和处理Callable任务中抛出的异常。通过具体的代码实现展示了线程池内部任务的异步串行执行过程。

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

 1 public class ThreadPoolTest {
 2     @Test
 3     public void testException(){
 4         try{
 5             testExecutorServiceException();
 6         }catch(Exception e){
 7             //e.printStackTrace();
 8             System.out.println("fa");
 9         }
10 
11     }
12     public void testExecutorServiceException() throws Exception{
13         Boolean flag = true;
14         //线程池,一个线程,线程池内部的任务是异步串行执行
15         ExecutorService executorService = Executors.newSingleThreadExecutor();
16         //results中存放任务执行的结果
17         List<Future<Boolean>> results = new ArrayList<Future<Boolean>>(10);
18         try{
19             for(int i=0; i<10; i++){
20                 Future<Boolean> future = executorService.submit(new ActSKUCacheCallable(i, flag));
21                /* if(false == future.get()){
22                     //throw new Exception("4324");
23                     //return;
24                 }*/
25                 //收集任务执行的结果,存储在results中
26                 results.add(future);
27             }
28             //主线程中执行,所以flag的值不一定是异步任务处理后的结果
29             System.out.println("结果:" + flag);
30             for(int i=0; i<10; i++){
31                 boolean flag1 = results.get(i).get();
32                 System.out.println("执行结果:" + flag1);
33             }
34 
35         }catch(Exception e){
36             //e.printStackTrace();
37             throw e;
38         }
39     }
40 
41     private class ActSKUCacheCallable implements Callable<Boolean> {
42         int i;
43         Boolean flag;
44         ActSKUCacheCallable(int i, Boolean flag){
45             this.i = i;
46             this.flag = flag;
47         }
48         public Boolean call() throws Exception {
49             try {
50                 if(i % 2 != 0){
51                     throw new Exception("try");
52                 }
53                 System.out.println("正常执行");
54             } catch (Exception e) {
55                 System.out.println("catch");
56                 //flag = false;
57                 //抛出异常不影响线程池中其他任务的执行
58                 throw e;
59                 //return Boolean.FALSE;
60             } finally {
61                 System.out.println("finally 代码块" + flag);
62             }
63 
64             System.out.println("try代码块外面");
65             return Boolean.TRUE;
66         }
67     }
68 }

执行结果:

 

转载于:https://www.cnblogs.com/zhima-hu/p/9152454.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值