如何要求CompletableFuture使用非守护线程? [英] How to ask CompletableFuture use non-daemon threads?

查看:337
本文介绍了如何要求CompletableFuture使用非守护线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码:

 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆