gpt4 book ai didi

java - 将 Future 与 ExecutorService 结合使用

转载 作者:行者123 更新时间:2023-12-01 21:53:31 25 4
gpt4 key购买 nike

我需要并行执行两个任务并等待它们完成。我还需要第二个任务的结果,因为我正在使用 Future

我的问题是,我需要 executor.awaitTermination 来加入任务,还是 Future.get() 会处理它。还有更好的方法可以使用 Java 8 实现此目的吗?

public class Test {

public static void main(String[] args) {
test();
System.out.println("Exiting Main");
}

public static void test() {
System.out.println("In Test");
ExecutorService executor = Executors.newFixedThreadPool(2);

executor.submit(() -> {
for(int i = 0 ; i< 5 ; i++) {
System.out.print("["+i+"]");
try {
Thread.sleep(1000);
} catch (Exception e) {e.printStackTrace();}
}
});

Future<String> result = executor.submit(() -> {
StringBuilder builder = new StringBuilder();
for(int i = 0 ; i< 10 ; i++) {
System.out.print("("+i+")");
try {
Thread.sleep(1000);
} catch (Exception e) {e.printStackTrace();}
builder.append(i);
}
return builder.toString();
});

System.out.println("shutdown");
executor.shutdown();
// DO I need this code : START
System.out.println("awaitTermination");
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
System.out.println("Error");
}
// DO I need this code : END
System.out.println("Getting result");
try {
System.out.println(result.get());
}
catch (InterruptedException e) {e.printStackTrace();}
catch (ExecutionException e) {e.printStackTrace();}
System.out.println("Exiting Test");
}

}

带有awaitTermination的输出:

In Test
[0]shutdown
(0)awaitTermination
[1](1)[2](2)[3](3)[4](4)(5)(6)(7)(8)(9)Getting result
0123456789
Exiting Test
Exiting Main

不带awaitTermination的输出:

In Test
[0]shutdown
Getting result
(0)[1](1)[2](2)[3](3)[4](4)(5)(6)(7)(8)(9)0123456789
Exiting Test
Exiting Main

最佳答案

获取 javadoc:

Waits if necessary for the computation to complete, and then retrieves its result.

get 将仅等待第二个任务。

来自 awaitTermination javadoc:

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

awaitTermination 将等待所有任务。

关于java - 将 Future 与 ExecutorService 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793424/

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