如何询问 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

并完成。

如何改变这种行为?

P.S. 我在 runAsync java 文档中没有看到任何相关内容

runAsync()javadoc 说:

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。

添加这一行:

ForkJoinPool.commonPool().awaitTermination(5, TimeUnit.SECONDS);

到运行你的未来之后的主要方法。我会阻塞,直到池中的所有任务都完成。

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