Java並發編程Callable與Future的應用執行個體代碼,callable應用執行個體

來源:互聯網
上載者:User

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的應用執行個體代碼的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.