0

我是 Vert.x 异步编程的新手。我想知道如何使用期货并行运行多个任务。(与使用 Java 的 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

4

1 回答 1

0

这段代码有两个问题:

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

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

最好的解决方案是首先重写fib以返回Future<Long>

于 2020-12-13T19:32:55.773 回答