简体   繁体   English

使用ThreadPool顺序执行类似的任务

[英]Executing similar tasks sequentially with ThreadPool

I want a ThreadPool to execute customer orders, multiple orders should be processed parallel, but for the same customer orders should be processed in a generated sequence. 我想要一个ThreadPool执行客户订单,应该并行处理多个订单,但是对于相同的客户订单应按生成的顺序进行处理。 Which means if any thread already processing customerA order then no other thread can process CustomerA's next order until first order is processed. 这意味着,如果有任何线程已经在处理customerA订单,那么在处理第一个订单之前,没有其他线程可以处理CustomerA的下一个订单。

Are there any ThreadPool implementations which serve my case ? 有没有适合我的情况的ThreadPool实现?

I do not think that there are such standard functionality of ThreadPools . 我认为ThreadPools没有这种标准功能。 What you need to do is to create 'dispatcher' that will 'assign threads' from pool to customer orders. 您需要做的是创建“分配器”,该“分配器”将从池中“分配线程”到客户订单。 It should save an internal map of unique order id -> thread . 它应该保存一个unique order id -> thread的内部映射。 If there is an order in processing new updates for this order should wait. 如果有订单正在处理新更新,则此订单应等待。

For this task you should look into actor model (and akka - as it's implementation). 对于此任务,您应该研究角色模型(以及akka-实现)。 It allows easily describe this solution. 它可以轻松描述此解决方案。

Simple implementation: 简单实施:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM