如何要求CompletableFuture使用非守护线程? [英] How to ask CompletableFuture use non-daemon threads?
问题描述
我写了以下代码:
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
并完成操作。
如何更改此行为?
PS >在 runAsync
java doc
P.S. I don't see anything related in runAsync
java doc
推荐答案
中没有任何相关内容 javadoc 对于 runAsync()
说:
The javadoc for runAsync()
says:
返回一个新的CompletableFuture在执行给定操作后,由ForkJoinPool.commonPool()中运行的任务异步完成。
Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() after it runs the given action.
还有另一个 版本的 runAsync()
,您可以在其中传递 ExecutorService。
There is another version of runAsync()
where you can pass an ExecutorService.
因此:当默认 commonPool()不执行您想要的操作-然后创建您自己的ExecutorService。
Thus: when the default commonPool() doesn't do what you want - then create your own ExecutorService instead.
这篇关于如何要求CompletableFuture使用非守护线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!