future3 = CompletableFuture.supplyAsync(() -> {
+ //逻辑C
+ log.info("C");
+ return "C";
+ }, executor);
+
+ CompletableFuture.allOf(future1, future2, future3)
+ .handle((result, exception) -> {
+ if (exception != null) {
+ log.error("处理失败:{}", exception);
+ } else {
+ //等待三个任务执行完 接着处理这个逻辑
+
+ }
+ return null;
+ });
+ }
+
+
+ /**
+ * 修改for循环为并行操作
+ *
+ * 这里借鉴了parallelStream流的思路,将串行的for循环分割成多个集合后,对分割后的集合进行循环。这应该是最普遍的多线程应用场景了
+ */
+ @Test
+ public void threadDemo2() throws Exception {
+
+ List slAddList = new ArrayList<>(50000);
+ slAddList.addAll(Arrays.asList("1", "2", "3", "4", "5", "6"));
+
+ List> partition = Lists.partition(slAddList, 2);
+
+ CompletableFuture.allOf(partition.stream().map(partitionList -> CompletableFuture.runAsync(() -> {
+ log.info("处理逻辑partitionList");
+ }, executor)
+ ).toArray(CompletableFuture[]::new))
+ .whenComplete((res, e) ->
+ {
+ if (e != null) {
+ log.error("多线程处理数据失败", e);
+ } else {
+ try {
+ log.info("进一步处理循环后的结果");
+ } catch (Exception ex) {
+ log.error("处理失败", ex);
+ }
+ }
+ });
+
+ }
+
+ /**
+ * 修改Map遍历为并行操作
+ */
+ @Test
+ public void threadDemo3() throws Exception {
+ //代码示例
+ Map> materialMap = new HashMap>() {
+ {
+ put("name", Arrays.asList("a","b","c"));
+ put("age", Arrays.asList("1","2","3"));
+ put("city", Arrays.asList("nj","bj","cz"));
+ put("province", Arrays.asList("js","zj","hn"));
+ put("love", Arrays.asList("bk","jk","bk"));
+ }
+ };
+ List