什么是等待可完成的未来线程完成的推荐方法 [英] What is the recommended way to wait till the Completable future threads finish

查看:100
本文介绍了什么是等待可完成的未来线程完成的推荐方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 CompletableFuture ,如下面的代码所示。但关于我应该等到所有可运行完成的方式,我找到了两种方法,我不知道它们之间的区别,哪一种是最佳实践?它们如下:

I am using CompletableFuture as shown below in the code. But concerning the way I should wait till all runnables finish, I found two ways and I do not know the difference between them and which one is the best practice? They are as follows:

代码

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);

等待所有runnables完成的第一种方法

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

等待所有runnables完成的第二种方法

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

请告诉我推荐哪一个。

推荐答案

只有当执行程序(growSeedExecutor)仅用于给定任务时,两种方式才相同。第一种方式可能导致以下:另一个任务需要并行化,并为每个任务创建新的执行程序。一些开发人员看到创建了太多执行程序,并决定使用单个通用执行程序,但未能删除所有执行程序关闭...

Both ways are equivalent only when the executor (growSeedExecutor) is used solely for the given task. The first way may lead to following: Another tasks need parallelization, and new executor is created for each task. Some developer sees too many executors created, and decide to use single common executor, but failed to delete all executor shutdowns...

所以第二种方式(join())更可靠,因为不太复杂。但是每个新的未来都应该添加到growSeedFutureList中,而不是分配给。

So the second way (join()) is more reliable, since is less complex. But each new future should be added to the growSeedFutureList, not assigned to.

这篇关于什么是等待可完成的未来线程完成的推荐方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆