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();
請讓我知道哪一個是推薦
兩者都可以工作,因此它取決於你想要對執行者做什麼:如果你不再需要它使用前者 - 如果你想重用它,使用後者...在你的第一個代碼中snippet只保留對最後一個CompletableFuture的引用... – assylias