Java 如何要求CompletableFuture使用非守护进程线程?
我编写了以下代码:Java 如何要求CompletableFuture使用非守护进程线程?,java,concurrency,daemon,future,completable-future,Java,Concurrency,Daemon,Future,Completable Future,我编写了以下代码: System.out.println("Main thread:" + Thread.currentThread().getId()); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { try { System.out.println("Before sleep thread:" + Thread.currentThread().getId
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()));
和完成
我怎样才能改变这种行为
p.S.我在runAsync
java文档中没有看到任何相关内容forrunAsync()
返回新的CompletableFuture,该Future由运行给定操作后在ForkJoinPool.commonPool()中运行的任务异步完成
还有另一个版本的runAsync()
可以传递执行器服务
因此:当默认设置不满足您的要求时,请创建您自己的ExecutorService。添加此行:
ForkJoinPool.commonPool().awaitTermination(5, TimeUnit.SECONDS);
在运行完你的未来之后,使用主方法。我将阻止,直到池中的所有任务都已完成
阻塞,直到所有任务在关闭请求后完成执行,或超时发生,或当前线程中断(以先发生的为准)
之后还是之前?之后。我把它放在main
方法的最后一行。
ForkJoinPool.commonPool().awaitTermination(5, TimeUnit.SECONDS);