CompletableFuture:几个任务 [英] CompletableFuture: several tasks

查看:134
本文介绍了CompletableFuture:几个任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用5个CompletableFutures异步执行20个可运行任务(或1个任务20次)?

How can I asynchronously execute 20 Runnable tasks(or 1 task 20 times), using 5 CompletableFutures?

这就是我所拥有的:

Runnable task = () -> {
        long startTime = System.currentTimeMillis();
        Random random = new Random();

        while (System.currentTimeMillis() - startTime < 3000) {
            DoubleStream.generate(() -> random.nextDouble())
                    .limit(random.nextInt(100))
                    .map(n -> Math.cos(n))
                    .sum();
        }
        System.out.println("Done");
    };

    for (int i = 0; i < 4; i++) {
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(task);
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(task);
        CompletableFuture<Void> future3 = CompletableFuture.runAsync(task);
        CompletableFuture<Void> future4 = CompletableFuture.runAsync(task);
        CompletableFuture<Void> future5 = CompletableFuture.runAsync(task);
        future1.get();
        future2.get();
        future3.get();
        future4.get();
        future5.get();
    }

如果执行此代码,则可以看到它仅异步运行3 future.get(): 3,然后在1 for()迭代期间剩下2.

If I execute this code, I can see that it only runs 3 future.get() asynchronously: 3 and then 2 that's left during 1 for() iteration

所以,我想尽可能异步地完成所有20个任务

So, I would like to do all 20 tasks, as asynchronously as possible

推荐答案

您可以使用allOf同时运行多个任务.首先,我创建了一个包含5个任务的组合(与您的问题相同),但是后来我添加了10个任务(并且只失败了两次),并获得了一半的执行时间.

You can use allOf to run several tasks simultaneously as one. First I create a combined of 5 tasks (the same as in your question) but then I added 10 instead (and only loped twice) and got half the execution time.

for (int i = 0; i < 2; i++) {
   CompletableFuture<Void> future1 = CompletableFuture.runAsync(task);
   CompletableFuture<Void> future2 = CompletableFuture.runAsync(task);
  // and so on until ten  
   CompletableFuture<Void> future10 = CompletableFuture.runAsync(task);

   CompletableFuture<Void> combined = CompletableFuture.allOf(future1, future2, future3, future4, future5, future6, future7, future8, future9, future10);

   combined.get();
}

这篇关于CompletableFuture:几个任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆