【发布时间】:2015-08-22 17:35:11
【问题描述】:
我正在使用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();
请告诉我推荐哪一个。
【问题讨论】:
-
两者都可以工作,所以这取决于你想对执行者做什么:如果你不再需要它,使用前者 - 如果你想重用它,使用后者......同样在您的第一个代码 sn-p 中,您只保留对最后一个 CompletableFuture 的引用...
-
我不太明白
this.growSeedFutureList =。growSeedFutureList的类型是什么?这是将元素添加到列表的一些新语法吗?有人可以澄清一下吗?有没有办法在没有列表的情况下实现这一点?
标签: java multithreading concurrency completable-future