2017-09-04 89 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'方法的最後一行。 –