假设我需要处理3种类型的请求: A、B和C,如下所示:
更一般情况下,类型数为N,并发请求数为K <= N。
如何用java.util.concurrent在Java中实现它?
发布于 2013-10-11 07:33:36
您不能同时处理K请求,这将打破第二条规则。并发请求的最大数量是数字类型。在你的情况下是三次。所以,建立三个队列,并将它们添加到三个线程中。这是唯一的办法。Executors.newSingleThreadExecutor实现了这一技术。
public static void main(String[] args) {
int N = 2;
int K = 3;
List<Executor> executors = new ArrayList<Executor>(N);
for(int i = 0; i < N; i++){
executors.add(Executors.newSingleThreadExecutor());
}
Map<Type, Executor> typeExecutors = new HashMap<Type, Executor>(K);
int i = 0;
for(Type t : Type.values()){
typeExecutors.put(t, executors.get(i++ % executors.size()));
}
}
enum Type{
T1, T2, T3
}发布于 2013-10-11 07:30:37
我会创建三个Executors.newFixedThreadPool(1)
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)
使用一个工厂委托,每个执行者的每个执行。
ExecutorService executor = ThreadFactory.getExecutorForRequest(RequestType type);
executor.execute(request);发布于 2013-10-11 07:31:12
请求是同时处理的。
你可以使用遗嘱执行人服务。
最多只能同时处理K个请求。
在executor中,设置最大线程数。
同一类型的请求不能同时处理。
您可能认为每种请求类型都有不同的锁。只要确保一个线程在指定的时间内无法获得请求的锁,它就会产生并进行下一个任务处理。
https://stackoverflow.com/questions/19312519
复制相似问题