繁体   English   中英

如何询问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 runAsync不到任何相关runAsync

runAsync()javadoc说:

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

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

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

添加此行:

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

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

阻止所有任务在关闭请求之后完成执行,或者发生超时,或者当前线程被中断,以先发生者为准。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM