栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java 8方法参数列表的并行流

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 8方法参数列表的并行流

看起来很冗长,但是您可以尝试以下方法。该

runAsync()
方法将使列表块并行运行。

private void test(List<Object> list, int chunkSize) throws ExecutionException, InterruptedException {    AtomicInteger prev = new AtomicInteger(0);    List<CompletableFuture> futures = new ArrayList<>();    IntStream.range(1, (int) (chunkSize * (Math.ceil(Math.abs(list.size() / (double) chunkSize))))) .filter(i -> i % chunkSize == 0 || i == list.size()) .forEach(i -> {     List<Object> chunk = list.subList(prev.get(), i);     futures.add(CompletableFuture.runAsync(() -> invokeList(chunk)));     prev.set(i); });    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();}private void invokeList(List<Object> list) {    System.out.println("Invoked for: " + list);}

为30个 整数 列表 运行,其 块大小为5, 如下所示:

public static void main(String[] args) throws ExecutionException, InterruptedException {    List<Object> list = IntStream.range(0, 30).mapToObj(i1 -> (Object) String.valueOf(i1)).collect(Collectors.toList());    int chunkSize = 5;    new Test().test(list, chunkSize);}

输出

Invoked for: [15, 16, 17, 18, 19]Invoked for: [0, 1, 2, 3, 4]Invoked for: [5, 6, 7, 8, 9]Invoked for: [10, 11, 12, 13, 14]Invoked for: [20, 21, 22, 23, 24]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/515578.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号