Java并發(fā)編程Callable與Future的應用實例代碼
本文主要探究的是java并發(fā)編程callable與future的使用,分享了相關實例代碼,具體介紹如下。
我們都知道實現(xiàn)多線程有2種方式,一種是繼承Thread,一種是實現(xiàn)Runnable,但這2種方式都有一個缺陷,在任務完成后無法獲取返回結果。要想獲得返回結果,就得使用Callable,Callable任務可以有返回值,但是沒法直接從Callable任務里獲取返回值;想要獲取Callabel任務的返回值,需要用到Future。所以Callable任務和Future模式,通常結合起來使用。
試想一個場景:需要一個帖子列表接口,除了需要返回帖子列表之外,還需要返回每條帖子的點贊列表和評論列表。一頁10條帖子來計算,這個接口需要訪問21次數(shù)據(jù)庫,訪問一次數(shù)據(jù)庫按100ms計算,21次,累計時間為2.1s。這個響應時間,怕是無法令人滿意的。怎么辦呢?異步化改造接口。
查出帖子列表后,迭代帖子列表,在循環(huán)里起10個線程,并發(fā)去獲取每條帖子的點贊列表,同時另起10個線程,并發(fā)去獲取每條帖子的評論列表。這樣改造之后,接口的響應時間大大縮短,在200ms。這個時候就要用Callabel結合Future來實現(xiàn)。
private List<PostResponse> createPostResponseList(Page<PostResponse> page,final String userId){ if(page.getCount()==0||page==null||page.getList()==null){ return null; } //獲取帖子列表 List<PostResponse> circleResponseList = page.getList(); int size=circleResponseList.size(); ExecutorService commentPool = Executors.newFixedThreadPool(size); ExecutorService supportPool = Executors.newFixedThreadPool(size); try { List<Future> commentFutureList = new ArrayList<Future>(size); if (circleResponseList != null && circleResponseList.size() > 0) { for (PostResponse postResponse : circleResponseList) { final String circleId=postResponse.getId(); final String postUserId=postResponse.getUserId(); //查評論列表 Callable<List<CircleReviews>> callableComment = new Callable<List<CircleReviews>>() { @Override public List<CircleReviews> call() throws Exception { return circleReviewsBiz.getPostComments(circleId); } }; Future f = commentPool.submit(callableComment); commentFutureList.add(f); //查點贊列表 Callable<List<CircleZan>> callableSupport = new Callable<List<CircleZan>>() { @Override public List<CircleZan> call() throws Exception { return circleZanBiz.findList(circleId); } }; Future supportFuture = supportPool.submit(callableSupport); commentFutureList.add(supportFuture); } } // 獲取所有并發(fā)任務的執(zhí)行結果 int i = 0; PostResponse temp = null; for (Future f : commentFutureList) { temp = circleResponseList.get(i); temp.setCommentList((List<CircleReviews>) f.get(); temp.setSupportList((List<CircleZan>) f.get(); circleResponseList.set(i, temp); i++; } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉線程池 commentPool.shutdown(); supportPool.shutdown(); } return circleResponseList; }
總結
以上就是本文關于Java并發(fā)編程Callable與Future的應用實例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
Java8新特性之精簡的JRE詳解_動力節(jié)點Java學院整理
這篇文章主要介紹了Java8新特性之精簡的JRE詳解的相關資料,需要的朋友可以參考下2017-06-06舉例講解Java的Spring框架中AOP程序設計方式的使用
這篇文章主要介紹了Java的Spring框架中AOP程序設計方式的使用講解,文中舉的AOP下拋出異常的例子非常實用,需要的朋友可以參考下2016-04-04Java中ThreadLocal線程變量的實現(xiàn)原理
本文主要介紹了Java中ThreadLocal線程變量的實現(xiàn)原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06