From a0873e29357eddb92dcc42f748db78115145ed86 Mon Sep 17 00:00:00 2001 From: xiangwb Date: Sat, 3 Feb 2018 13:05:48 +0800 Subject: [PATCH] merge --- .../main/java/com/xwbing/demo/LambdaDemo.java | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java b/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java index 8843028..f613436 100644 --- a/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java +++ b/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java @@ -3,6 +3,7 @@ package com.xwbing.demo; import com.alibaba.fastjson.JSONObject; import com.xwbing.domain.entity.sys.SysUser; import com.xwbing.domain.entity.sys.SysUserRole; +import com.xwbing.exception.BusinessException; import com.xwbing.service.sys.SysUserRoleService; import com.xwbing.service.sys.SysUserService; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @@ -87,14 +88,38 @@ public class LambdaDemo { reduce = optional.get(); } //异步回调 - CompletableFuture> future = CompletableFuture.supplyAsync(LambdaDemo::getList, taskExecutor); +// CompletableFuture> future = CompletableFuture.supplyAsync(LambdaDemo::getList, taskExecutor);//添加时候可以用任务线程池 + CompletableFuture> future = CompletableFuture.supplyAsync(LambdaDemo::getList);//查询不需要任务线程池 try { - List sysUsers = future.get(); + List sysUsers = future.get(); } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); + throw new BusinessException(""); } } + /** + * 遍历集合,集合里数据还要进行复杂操作,导致速度很慢,可以用异步 + */ + public List supplyAsync() { + List list = getList(); + int size = list.size(); + CompletableFuture[] futures = new CompletableFuture[size]; + List finalList = new ArrayList<>(); + for (int i = 0; i < size; i++) { + JSONObject object = list.get(i); + if (object != null) { + futures[i] = CompletableFuture.supplyAsync(() -> finalList.add(setData(object)), taskExecutor); + } + } + CompletableFuture completableFuture = CompletableFuture.allOf(futures); + try { + completableFuture.get(); + } catch (InterruptedException | ExecutionException e) { + throw new BusinessException("获取数据出错"); + } + return finalList; + } + /** * filter * @@ -115,7 +140,12 @@ public class LambdaDemo { } } - public static List getList() { + public static List getList() { return null; } + + public JSONObject setData(JSONObject object) { + return object; + } + }