如何使用Java 8 Streams同时或并行运行3种方法

use*_*894 -2 java parallel-processing java-8

1)敏锐地知道如何使用Java 8并行运行Method1、2、3

2)这是使用流8满足我的要求的正确方法吗?

public void RunParallel()
{
    String method1 = method1();
    String method2 = method2();
    String method3 = method3(String Value);
}
Run Code Online (Sandbox Code Playgroud)

Stream.<Runnable>of(() -> method1(),() -> method2(),() -> method3()).parallel().forEach(Runnable::run);

kar*_*ivi 5

您可以使用Java 8进行以下操作,并同时运行以下代码method1,method2和method3。如果您想在全部完成后做某事,则可以使用future.get();。

public void RunParallel()
{
    CompletableFuture<Void> future1 = CompletableFuture.runAsync(()->{
        String method1 = method1();
    });

    CompletableFuture<Void> future2 = CompletableFuture.runAsync(()->{
        String method2 = method2();
    });

    CompletableFuture<Void> future3 = CompletableFuture.runAsync(()->{
        String method3 = method3("some inp");
    });

    CompletableFuture<Void> future = CompletableFuture.allOf(future1, future2, future3); 
    try {
        future.get(); // this line waits for all to be completed
    } catch (InterruptedException  | ExecutionException e) {
        // Handle
    }
}
Run Code Online (Sandbox Code Playgroud)