2015-06-08 59 views
7

我正在使用CompletableFuture,如下面的代碼所示。但是關於我應該等到所有可運行結束的方式,我找到了兩種方法,我不知道它們之間的區別,哪一個是最佳做法?他們 如下:什麼是等待完成的未來線程完成的推薦方式

代碼

this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedSERun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor); 
      this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedNWRun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor); 
      this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedNERun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor); 
      this.growSeedFutureList = CompletableFuture.runAsync(new GrowSeedSWRun(this.saliencyMat, this.seedXY, this.seedVal), this.growSeedExecutor); 

第一種方式要等到所有可運行完成

this.growSeedExecutor.shutdown(); 
this.growSeedExecutor.awaitTermination(1, TimeUnit.DAYS); 

第二種方法要等到所有可運行完成

CompletableFuture.allOf(this.growSeedFutureList).join(); 

請讓我知道哪一個是推薦

+2

兩者都可以工作,因此它取決於你想要對執行者做什麼:如果你不再需要它使用前者 - 如果你想重用它,使用後者...在你的第一個代碼中snippet只保留對最後一個CompletableFuture的引用... – assylias

回答

4

兩種方式都是隻有在執行(growSeedExecutor)僅用於給定的任務等同。第一種方式可能導致以下情況:另一項任務需要並行化,併爲每項任務創建新的執行程序。有些開發人員看到創建的執行者太多,並決定使用單個通用執行程序,但未能刪除所有執行程序關閉...

因此,第二種方法(join())更加可靠,因爲它更簡單。但是每個新的未來都應該添加到growSeedFutureList中,而不是分配給。