等待 Java 线程池中的线程子集
假设我有一个包含 X
项的线程池,并且给定任务使用这些项中的 Y
(其中 Y
比 Y
小得多) >X)。
我想等待给定任务(Y
项)的所有线程完成,而不是整个线程池。
如果线程池的 execute()
方法返回对所使用线程的引用,我可以简单地 join()
到这些 Y
线程中的每一个,但是事实并非如此。
有谁知道一种优雅的方法来实现这一点?谢谢。
Let's say I have a thread pool containing X
items, and a given task employs Y
of these items (where Y
is much smaller than X
).
I want to wait for all of the threads of a given task (Y
items) to finish, not the entire thread pool.
If the thread pool's execute()
method returned a reference to the employed thread I could simply join()
to each of these Y
threads, but it doesn't.
Does anyone know of an elegant way to accomplish this? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建以
Y
作为计数的CountDownLatch
,并在每个Y
任务中执行latch.countDown()
。最后,latch.await()
将确保所有Y
任务都完成。Create
CountDownLatch
withY
as count and dolatch.countDown()
in each ofY
tasks. In the endlatch.await()
will ensure that all of theY
tasks are completed.您可以使用 CyclicBarrier 并让每个线程仅在其类型为 Y 时等待。例如。
因此,运行类型 Y 的每个线程都会等待,直到所有这些 Y 都完成。请注意,您必须将屏障大小加 1,以考虑到最初执行的线程也将等待。
另请注意:如果迈克尔·博格沃特的示例适合您,那就最好了。但是,如果您需要线程池,对于运行 Y 的每个线程不运行任何其他非 Y 线程,那么我的解决方案将是您可以做到这一点的唯一方法。 Future.get() 只会阻塞调用线程,当线程池完成 Y 的执行时,它将开始执行一些其他(可能是非 Y)任务。
You can use a CyclicBarrier and have each thread wait only when it is of type Y. For example.
So each thread that is running type Y will wait until all those Y's have completed. Note you have to add 1 to the barrier size to account for the initially executing thread to wait also.
Also Note: If Michael Borgwardt's example works for you that would be best. However, if you need the thread pool, for each thread that is running Y to not run any other non-Y's then my solution would be the only way you can do it. Future.get() will only block the calling thread, and when the thread pool finishes Y's execution it will then pick up some other (possibly non-Y) task.
而不是
execute()
ingRunnable
,只需invokeAll()
一些Callable
- 然后你为每个对象获取一个Future
,您可以在其上调用get()
,它会阻塞直到任务完成。Instead of
execute()
ingRunnable
s, justinvokeAll()
someCallable
s - then you get aFuture
for each on which you can callget()
, which blocks until the task is finished.您应该使用
CompletionService
正是用于此目的。Executor
ExecutorCompletionService
通过CompletionService
提交任务take
或poll
在 CompletionService 上等待任务完成您可以与其他东西共享 Executor,只需在顶部创建
CompletionService
并将其用于您的特定任务任务。You should use a
CompletionService
which is used for exactly this purpose.Executor
ExecutorCompletionService
using the ExecutorCompletionService
take
orpoll
on the CompletionService to wait for the tasks to finishYou can share an Executor with something else, just create the
CompletionService
over the top and use it for your specific tasks.