Callable拋出異常與future.get

 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 }

執行結果:異步

相關文章
相關標籤/搜索