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次數據庫,訪問一次數據庫按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的應用實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
springboot快速整合Mybatis組件的方法(推薦)
Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發(fā)過程。這篇文章主要介紹了springboot快速整合Mybatis組件的方法,需要的朋友可以參考下2019-11-11
SpringBoot使用MyBatis時的幾種傳參規(guī)范示例
使用Mybatis作為持久層框架時,對于數據庫的增刪改查等操作都需要參數的傳遞,本文就詳細的介紹了一下SpringBoot使用MyBatis時的幾種傳參規(guī)范示例,感興趣的可以了解一下2022-02-02

