为什么在CompletableFuture中时,我的Thread.sleep会结束进程? [英] Why is my Thread.sleep ending my process when inside a CompletableFuture?
问题描述
我正在尝试创建CompleteableFuture.我只是想注销一些声明.这是我的代码:
I am trying to create a CompleteableFuture. I am just trying to log out a few statements. Here is my code:
static CompletableFuture<String> createFuture(String name) {
return CompletableFuture.supplyAsync(() -> {
try {
System.out.println("Task execution started.");
//Thread.sleep(2000);
System.out.println("Task execution stopped.");
} catch (Exception e) {
e.printStackTrace();
}
return name;
});
}
static void start(Person person, List<Person> people) {
CompletableFuture.allOf(
createFuture("Bob")
).thenApply(s -> {
return s;
}).exceptionally(e -> {
System.out.println(e);
return null;
});
}
一切正常,直到我取消注释 Thread.sleep(2000)
.如果不加注释,该过程将终止.它不会进入 catch
,也不会进入 exception
.为什么?我想念什么?我该如何进行这项工作?
Everything works fine, until I uncomment Thread.sleep(2000)
. When uncommented, the process dies. It doesn't go into the catch
and it doesn't go into the exceptionally
. Why? What am I missing? How do I make this work?
推荐答案
问题是,当执行者执行时, CompletableFuture.supplyAsync
使用常见的 JoinForkPool
来执行供应商.除非另有定义.正如用户VGR在问题注释中指出的那样,应用程序不等待任务完成-这是因为JoinForkPool中的线程都是守护程序,这意味着它们不会阻止应用程序在运行时关闭
The problem is that CompletableFuture.supplyAsync
uses the common JoinForkPool
to execute the supplier when an executor is not otherwise defined. As pointed out by user VGR in the question comments, the application is not waiting for the tasks to complete - this is because the threads in a JoinForkPool are all daemons, meaning that they do not block the application from shutting down while they're running.
解决方案是使用采用 Executor
的 supplyAsync
版本,并使用非 JoinForkPool
执行程序,因此线程不是守护程序或获取公用池并执行某些操作以使池等待,例如 awaitTermination
方法.
The solution is to use the version of supplyAsync
that takes an Executor
and use a non-JoinForkPool
executor so the threads are not daemons or get the common pool and do something to cause the pool to wait, such as the awaitTermination
method.
这篇关于为什么在CompletableFuture中时,我的Thread.sleep会结束进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!