我需要并发处理一些Collection实例中的元素。换句话说,而不是迭代一个Collection实例
for (Someclass elem : coll){
process(elem);
}
我想同时处理这些元素。比如说,像ConcurrentCollectionExecutor(coll, new Callable{…}, numberOfThreads)
这样的东西。此外,还应修复多个并发线程。
是否已经存在任何灵活的模式?
发布于 2013-02-08 16:32:36
使process方法成为一个名为MyRunnable的类中的run()方法,该类实现Runnable,其构造函数将elem作为输入并将其存储为实例变量。然后使用:
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
for (Someclass elem : coll){
Runnable worker = new MyRunnable(elem);
executor.execute(worker);
}
发布于 2013-02-08 16:43:17
下面是这个executor类的“手工”版本。请注意,您必须传递的不是Callable
(或Runnable
)的实例,而是此类处理器类的类名。
public class ConcurrentCollectionExecutor<T> {
private Collection<T> collection;
private Class<Runnable> processor;
private int numberOfThreads;
private Executor executor;
public ConcurrentCollectionExecutor(Collection<T> collection, Class<Runnable> processor, int numberOfThreads) {
this.collection = collection;
this.processor = processor;
this.numberOfThreads = numberOfThreads;
this.executor = Executors.newFixedThreadPool(numberOfThreads);
}
public void run() {
try {
Constructor<Runnable> constructor = null;
for (T t : collection) {
if (constructor == null) {
constructor = processor.getConstructor(t.getClass());
}
executor.execute(constructor.newInstance(t));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
https://stackoverflow.com/questions/14768467
复制相似问题