gpt4 book ai didi

Java 等待所有线程完成

转载 作者:行者123 更新时间:2023-12-01 17:59:14 29 4
gpt4 key购买 nike

编辑:我的问题不同,它与链接的问题无关。

我使用完成处理程序跟踪代码。

FutureTask<Void> futureTask = new FutureTask<Void>(() -> {
System.out.println("callback");
return null;
});

Runnable task = () -> {
for(int i=0; i<5; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
futureTask.run();
};

new Thread(task).start();
new Thread(task).start();

基本上我正在寻找可变数量任务的完成处理程序,或者还有其他方法吗?

我受到了这个启发answer但当我寻找 native 解决方案时,它似乎是某个库的一部分。

Completable Future ???

这是我对可完成的 future 的尝试,最后有结果处理程序。

public void test() {
CompletableFuture
.supplyAsync(() -> method1())
.supplyAsync(() -> method2())
.supplyAsync(() -> result());
}

public String method1() {
System.out.println("calling 1");
return "method1";
}

public String method2() {
System.out.println("calling 2");
return "method2";
}

public String result() {
System.out.println("result");
return "result";
}

最佳答案

假设您的方法 result() 返回一个您想要检索的值,即声明为 Type result(),您可以使用

CompletableFuture<Type> f = CompletableFuture.allOf(
CompletableFuture.runAsync(() -> method1()),
CompletableFuture.runAsync(() -> method2())
).thenApply(_void -> result());

每个runAsync都会创建一个单独的异步CompletableFuture,该异步CompletableFuture将在执行Runnable后完成。它与 supplyAsync 相同,只是它不返回结果。

allOf 创建一个 CompletableFuture,一旦所有指定的 future 完成,它就会完成,因此,任何链接的依赖操作只会在所有 future 完成后运行。通过使用thenApply,我们创建了一个依赖的 future,它将通过 result() 的返回值完成。

如果 result() 不打算返回值,而只是在所有其他操作完成后运行的操作,则可以使用

CompletableFuture.allOf(
CompletableFuture.runAsync(() -> method1()),
CompletableFuture.runAsync(() -> method2())
).thenRun(() -> result());

相反。

关于Java 等待所有线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42282766/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com