2017-09-04 93 views
3

我已经写了下面的代码:如何问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 

和完成。

我该如何改变这种行为?

P.S.我没有看到任何东西runAsync Java文档相关

+0

@GhostCat,我只是在写测试,这种行为令我感到惊讶 – gstackoverflow

+0

@GhostCat感谢您的查询) – gstackoverflow

回答

6

javadocrunAsync()说:

返回一个新CompletableFuture是异步由ForkJoinPool.commonPool(运行任务完成)运行后给定的行动。

另一版本的runAsync()在那里你可以一个ExecutorService。

这样:当默认commonPool()不会做你想做的 - 然后创建自己的ExecutorService来代替。

2

添加这行:

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

到main方法运行你的未来了。我会阻止,直到池中的所有任务都完成。

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

+0

after或before? – gstackoverflow

+0

后。我把它放在'main'方法的最后一行。 –