Java並發編程Callable與Future的應用執行個體代碼,callable應用執行個體
本文主要探究的是java並發編程callable與future的使用,分享了相關執行個體代碼,具體介紹如下。
我們都知道實現多線程有2種方式,一種是繼承Thread,一種是實現Runnable,但這2種方式都有一個缺陷,在任務完成後無法擷取返回結果。要想獲得返回結果,就得使用Callable,Callable任務可以有傳回值,但是沒法直接從Callable任務裡擷取傳回值;想要擷取Callabel任務的傳回值,需要用到Future。所以Callable任務和Future模式,通常結合起來使用。
試想一個情境:需要一個貼文清單介面,除了需要返回貼文清單之外,還需要返回每條文章的點贊列表和評論列表。一頁10條文章來計算,這個介面需要訪問21次資料庫,訪問一次資料庫按100ms計算,21次,累計時間為2.1s。這個回應時間,怕是無法令人滿意的。怎麼辦呢?非同步化改造介面。
查出貼文清單後,迭代貼文清單,在迴圈裡起10個線程,並發去擷取每條文章的點贊列表,同時另起10個線程,並發去擷取每條文章的評論列表。這樣改造之後,介面的回應時間大大縮短,在200ms。這個時候就要用Callabel結合Future來實現。
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); } } // 擷取所有並發任務的執行結果 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並發編程Callable與Future的應用執行個體代碼的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!