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

gst*_*low 4 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(), + " 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()));
Run Code Online (Sandbox Code Playgroud)

这一个打印:

Main thread:1
Before sleep thread:11 isDaemon:true
Run Code Online (Sandbox Code Playgroud)

并完成.

我该如何改变这种行为?

PS我在runAsyncjava doc 中看不到任何相关内容

Gho*_*ica 7

javadoc中runAsync()说道:

返回一个新的CompletableFuture,它在运行给定操作后由ForkJoinPool.commonPool()中运行的任务异步完成.

还有另一个版本runAsync()可以传递 ExecutorService.

因此:当默认的commonPool()没有做你想要的 - 然后创建自己的ExecutorService.