ForkJoinPool的思想,是将大的集合进行拆分,计算处理之后,再把结果合并,这体现了多核时代的并行计算能力。
List<Integer> maps = Lists.newArrayList(); int count = 100; for (int i = 0; i < count; i++) { maps.add(i); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); List<Integer> odds = new ArrayList<>(); ForkJoinPool forkJoinPool = new ForkJoinPool(10); forkJoinPool.submit(() -> { maps.parallelStream() .forEach(map -> { if (map % 2 == 0) { odds.add(map); try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); }).join(); stopWatch.stop(); logger.info(stopWatch.prettyPrint());
ListUtil.split使用了hutool框架,5.4.5版本提供了集合拆分功能
//fork集合 List<List<Integer>> jihe = new ArrayList<>(); jihe = ListUtil.split(maps, 9); List<List<Integer>> finalJihe = jihe; forkJoinPool.submit(() -> { finalJihe.parallelStream() .forEach(map -> { logger.info("map size:{}", map.size()); }); }).join();