高效開發:Java中Future的使用(Future代表的是異步執行的結果)


1、Future是java 1.5引入的一個interface,可以方便的用於異步結果的獲取。

2、Future代表的是異步執行的結果,意思是當異步執行結束之后,返回的結果將會保存在Future中。

那么我們什么時候會用到Future呢? 一般來說,當我們執行一個長時間運行的任務時,使用Future就可以讓我們暫時去處理其他的任務,等長任務執行完畢再返回其結果。

經常會使用到Future的場景有:1. 計算密集場景。2. 處理大數據量。3. 遠程方法調用等,都是耗時比較長的需要等待的任務。

上代碼例子:Controller層

import java.util.concurrent.Future;
/** * 首頁異步請求統計接口 * * @return */ @RequestMapping(value = "/getAssetAsyncComponent", method = { RequestMethod.GET }) public BaseResult getAssetAsyncComponent() throws Exception { RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); long currentTimeMillis = System.currentTimeMillis(); Future<Map<String, Object>> countAssetInfoByAssetType = assetMgrAsyncComponentTask .countAssetInfoByAssetType(requestAttributes); Future<Map<String, Object>> getCountUnAsset = assetMgrAsyncComponentTask.getCountUnAsset(requestAttributes); Future<Map<String, Object>> getAssetFoundTaskTop = assetMgrAsyncComponentTask .getAssetFoundTaskTop(requestAttributes); Future<Map<String, Object>> listBusinessHomePage = assetMgrAsyncComponentTask .listBusinessHomePage(requestAttributes); Future<Map<String, Object>> getTop5Business = assetMgrAsyncComponentTask.getTop5Business(requestAttributes); for (;;) { if (countAssetInfoByAssetType.isDone() && getCountUnAsset.isDone() && getAssetFoundTaskTop.isDone() && listBusinessHomePage.isDone() && getTop5Business.isDone()) { // 5個任務都調用完成,退出循環等待 break; } Thread.sleep(300); } Map<String, Object> map = new HashMap<String, Object>(); map.put("countAssetInfoByAssetType", countAssetInfoByAssetType.get()); map.put("getCountUnAsset", getCountUnAsset.get()); map.put("getAssetFoundTaskTop", getAssetFoundTaskTop.get()); map.put("listBusinessHomePage", listBusinessHomePage.get()); map.put("getTop5Business", getTop5Business.get()); long currentTimeMillis1 = System.currentTimeMillis(); System.out.println("首頁 第一次請求的時候 異步獲取全部的數據 task任務總耗時:" + (currentTimeMillis1 - currentTimeMillis) + "ms"); return new BaseResult(map); }

  下一層加注解異步@Async即可

import org.springframework.scheduling.annotation.AsyncResult;
@Async
public Future<Map<String, Object>> countAssetInfoByAssetType(RequestAttributes requestAttributes) { Map<String, Object> resultsMap = new HashMap<String, Object>(); long begin = System.currentTimeMillis(); try { RequestContextHolder.setRequestAttributes(requestAttributes, true); BaseResult baseResult = assetInfoQueryService.countAssetInfoByAssetType(); resultsMap = (Map<String, Object>) baseResult.getData(); } catch (Exception e) { resultsMap.put("error", "countAssetInfoByAssetType 接口異常"); } long end = System.currentTimeMillis(); System.out.println("countAssetInfoByAssetType 接口 耗時(秒)=" + (end - begin) / 1000.0); return new AsyncResult<Map<String, Object>>(resultsMap); }

  也可以去看 https://blog.51cto.com/u_15287666/2976131 此博主的文章


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM