本文介绍了如何要求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

推荐答案

中没有任何相关内容对于 runAsync()说:

The javadoc for runAsync() says:

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

There is another version of runAsync() where you can pass an ExecutorService.

因此:当默认不执行您想要的操作-然后创建您自己的ExecutorService。

Thus: when the default commonPool() doesn't do what you want - then create your own ExecutorService instead.

这篇关于如何要求CompletableFuture使用非守护线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:27
查看更多