![](/img/trans.png)
[英]RejectedExecutionException when executing tasks using threadpool : JAVA
[英]Executing similar tasks sequentially with ThreadPool
我想要一个ThreadPool执行客户订单,应该并行处理多个订单,但是对于相同的客户订单应按生成的顺序进行处理。 这意味着,如果有任何线程已经在处理customerA订单,那么在处理第一个订单之前,没有其他线程可以处理CustomerA的下一个订单。
有没有适合我的情况的ThreadPool实现?
我认为ThreadPools
没有这种标准功能。 您需要做的是创建“分配器”,该“分配器”将从池中“分配线程”到客户订单。 它应该保存一个unique order id -> thread
的内部映射。 如果有订单正在处理新更新,则此订单应等待。
对于此任务,您应该研究角色模型(以及akka-实现)。 它可以轻松描述此解决方案。
简单实施:
public class CustomerOrderedExecutor {
private final Map<Integer, Executor> executors;
private final int poolSize;
public CustomerOrderedExecutor(int poolSize) {
this.poolSize = poolSize;
ImmutableMap.Builder<Integer, Executor> builder = ImmutableMap.builder();
for (int i = 0; i < poolSize; i++) {
builder.put(i, Executors.newSingleThreadExecutor());
}
executors = builder.build();
}
void execute(Runnable command, int customerId) {
executors.get(customerId % poolSize).execute(command);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.