问题描述
假设我有一个Runnable
对象的有序列表,这些对象将由ExecutorService
执行.我的Runnable
对象有一个userID
字段-假设我有 20 个不同的userId
-s,而 10 是池中的线程数(ExecutorService
对象).
Suppose I have an ordered list of Runnable
objects that are to be executed by ExecutorService
. My Runnable
objects have a userID
filed - let's say I have about 20 different userId
-s and 10 is the number of threads in the pool (ExecutorService
object).
什么是一般设计模式以确保最多同时在一个线程中执行特定组的1个Runnable
对象? (目标是一个ID组中的所有Runnable
应该按时间顺序并同步地执行).
What is a general design pattern to ensure that at most 1 Runnable
object of particular group is being executed in one of threads at one time? (The goal is that all Runnable
from one id group should be executed cronologically and synchronously).
推荐答案
您可以为每个组创建队列,当任务终止时,您将读取相应的队列,并在需要时提交下一个任务.
You could create queues for each group and when a task terminates you read the corresponding queue and submit the next task if needed.
为此,您需要以某种方式确定Runnable何时终止.使用标准的JDK类,您实际上不能通过简单的方法来做到这一点,而只能使用 Guava 库,您可以将ExecutorService包装到ListeningExecutorService中.如果您通过此包装程序提交任务,它将返回一个 ListenableFuture 普通的Java Future. ListenableFuture允许您注册在任务终止时将执行的回调.在这些回调中,您可以检查队列并在同一组中提交下一个任务.
For that you somehow need to identify when a Runnable terminates. With the standard JDK classes you cannot really do that in a simple way but using the Guava library you can wrap your ExecutorService into a ListeningExecutorService. If you submit a task through this wrapper it will return you a ListenableFuture instead of the plain Java Future. A ListenableFuture will let you register callbacks that will be executed when the task terminates. In these callbacks you can check your queues and submit the next tasks in the same group.
这篇关于设计模式以确保池仅执行一个具有特定id值的Runnable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!