gpt4 book ai didi

java - 如何询问 CompletableFuture 使用非守护线程?

转载 作者:搜寻专家 更新时间:2023-11-01 01:20:20 26 4
gpt4 key购买 nike

我写了下面的代码:

 System.out.println("Main thread:" + Thread.currentThread().getId());
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
System.out.println("Before sleep thread:" + Thread.currentThread().getId(), + " isDaemon:" + Thread.currentThread().isDaemon());
Thread.sleep(100);
System.out.println("After sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
future.whenComplete((r, e) -> System.out.println("whenCompleted thread:" + Thread.currentThread().getId()));

这一个打印:

Main thread:1
Before sleep thread:11 isDaemon:true

并完成。

我怎样才能改变这种行为?

P.S. 我在 runAsync java doc

中没有看到任何相关内容

最佳答案

javadoc对于 runAsync() 说:

Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() after it runs the given action.

另一个版本的 runAsync() 您可以在其中传递 ExecutorService。

因此:当默认commonPool()不做你想做的 - 然后创建你自己的 ExecutorService。

关于java - 如何询问 CompletableFuture 使用非守护线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032904/

26 4 0