我正在使用 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();
请告诉我推荐哪一个。
原文由 user2121 发布,翻译遵循 CC BY-SA 4.0 许可协议
仅当执行程序 (growSeedExecutor) 仅用于给定任务时,这两种方式才等效。第一种方式可能会导致以下情况:另一个任务需要并行化,并且为每个任务创建新的执行器。一些开发人员看到创建了太多执行器,并决定使用单个通用执行器,但未能删除所有执行器关闭…
所以第二种方式 (join()) 更可靠,因为它不那么复杂。但是每个新的未来都应该添加到 growSeedFutureList 中,而不是分配给。