遍历list时 多线程的使用

78 阅读1分钟

有关多线程

美团技术团队的博客中mp.weixin.qq.com/s/GQGidprak… 有一段Future的工具类,复制使用

gitee.com/phui/share-… b站up主有一个线程的封装工具类可以使用

使用future并发处理list

思路

map在遍历时是阻塞的,其中耗时会累加,但CompletableFuture可以快速遍历list中来创建多个异步任务,提高效率,返回一个List< CompletableFuture > 使用

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)

等待所有CF完成

.thenApply(v -> completableFutures.stream()
        .map(CompletableFuture::join)
        .filter(Objects::nonNull)
        .collect(Collectors.toList())
);

集合完成后,再使用::join方法获取到结果,返回一个结果的list

最后获取这个CompletableFuture<List<>>的值 (同样使用join)

image.png

测试代码

public class test {
    public static void main(String[] args) throws Exception {
        ArrayList<String> objects = new ArrayList<>();

        objects.add("1");
        objects.add("2");
        objects.add("3");


        List<String> collect = objects.stream().map(
                s -> {
                        SmallTool.sleepMillis(5000);
                        SmallTool.printTimeAndThread(s);

                    return s;
                }
        ).collect(Collectors.toList());

        SmallTool.printTimeAndThread(collect.toString());

        List<CompletableFuture<String>> collect1 = objects.stream().map(
                e -> {
                    CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(
                            () -> {
                                SmallTool.sleepMillis(5000);
                                SmallTool.printTimeAndThread(e);
                                return e;
                            });
                    return stringCompletableFuture;

                }
        ).collect(Collectors.toList());

        CompletableFuture<List<String>> listCompletableFuture = FutureUtils.sequenceNonNull(collect1);
        List<String> join = listCompletableFuture.join();
        SmallTool.printTimeAndThread(join.toString());


    }
}

运行结果

image.png

查看时间,第二种方式在不同线程中共同完成