【问题标题】:Vert.x -- How to Execute Tasks/Methods in Parallel Using FutureVert.x——如何使用 Future 并行执行任务/方法
【发布时间】:2021-03-24 06:12:32
【问题描述】:

我是 Vert.x 异步编程的新手。我想知道如何使用期货并行运行多个任务。 (Similar to this one using Java's callable)。

以下是我所拥有的,但任务是按顺序执行的。我错过了什么?

CompositeFuture.all(
                Future.future(h -> {
                        runTask("Future one");
                }),
                Future.future(h -> {
                        runTask("Future two");
                })
        ).onComplete(ar ->{
            if(ar.succeeded()){
                System.out.println("All succeeded");
            }
            else {
                System.out.println("At least one failed");
            }
        });

public static Future<Void> runTask(String m) {
        System.out.println("running " + m);

        System.out.println("30th fibonacci num is " + fib(30)); //Calling a method that calculates the nth fibonacci

        System.out.println("completed running " + m);

        return Future.<Void>succeededFuture();
    }

Output:
running Future one
Fib of 30 is 102334155
completed running Future one
running Future two
Fib of 30 is 102334155
completed running Future two
Done

But the expected output should be:
running Future one
running Future two
Fib of 30 is 102334155
Fib of 30 is 102334155
completed running Future one
completed running Future two
Done
Done

【问题讨论】:

    标签: vert.x vertx4


    【解决方案1】:

    这段代码有两个问题:

    1. 您的 fib() 方法被阻塞。
    2. 只有在阻塞代码完成后才能返回未来

    此外,你没有发布它,但我猜你是从 main() 方法执行的,这意味着 Vert.x 继承了被阻塞的单个主线程。

    最好的解决方案是首先重写fib 以返回Future&lt;Long&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多