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 }
执行结果: