2015-11-04 37 views
0

我想要一個ThreadPool執行客戶訂單,多個訂單應該被並行處理,但是對於相同的客戶訂單應該按照生成的順序進行處理。 這意味着如果有任何線程已經處理了customerA訂單,那麼沒有其他線程可以處理CustomerA的下一個訂單,直到處理完第一個訂單。使用ThreadPool按順序執行類似任務

是否有任何ThreadPool實現爲我的情況提供服務?

+0

內置那些不具有開箱即用,但你可以輕鬆地定製他們支持這一點。 – Kayaman

回答

1

我不認爲有ThreadPools這樣的標準功能。你需要做的是創建'調度員',將'分配線程'從池到客戶訂單。它應該保存內部地圖unique order id -> thread。如果處理新訂單的訂單應該等待。

對於這個任務,你應該看演員模型(和AKK - 因爲它的實現)。它可以輕鬆描述這個解決方案。

0

簡單實現:

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