问题描述
这里是我在哪里我don
长l;
迭代器< Long> i = getUserIDs();
while(i.hasNext()){
l = i.next();
someObject.doSomething(l);
anotheObject.doSomething(l);
}
迭代器对象,所以我不太担心。我想加快循环遍历迭代器需要多长时间,不要按顺序执行。
提前感谢。
一个解决方案是使用一个执行器来并行处理你的工作。
ExecutorService executor = Executors.newCachedThreadPool();
迭代器< Long> i = getUserIDs();
while(i.hasNext()){
final Long l = i.next();
Runnable task = new Runnable(){
public void run(){
someObject.doSomething(l);
anotheObject.doSomething(l);
}
}
executor.submit(task);
}
executor.shutdown();
这将为迭代器中的每个项目创建一个新的线程,然后它将执行工作。你可以通过在 Executors
类上使用不同的方法来调整使用多少线程,或者按照你认为合适的方式细分工作(例如不同的 Runnable
每个方法调用)。
I'm trying to loop over a Java iterator concurrently, but am having troubles with the best way to do this.
Here is what I have where I don't try to do anything concurrently.
Long l;
Iterator<Long> i = getUserIDs();
while (i.hasNext()) {
l = i.next();
someObject.doSomething(l);
anotheObject.doSomething(l);
}
There should be no race conditions between the things I'm doing on the non iterator objects, so I'm not too worried about that. I'd just like to speed up how long it takes to loop through the iterator by not doing it sequentially.
Thanks in advance.
One solution is to use an executor to parallelise your work.
Simple example:
ExecutorService executor = Executors.newCachedThreadPool();
Iterator<Long> i = getUserIDs();
while (i.hasNext()) {
final Long l = i.next();
Runnable task = new Runnable() {
public void run() {
someObject.doSomething(l);
anotheObject.doSomething(l);
}
}
executor.submit(task);
}
executor.shutdown();
This will create a new thread for each item in the iterator, which will then do the work. You can tune how many threads are used by using a different method on the Executors
class, or subdivide the work as you see fit (e.g. a different Runnable
for each of the method calls).
这篇关于Java迭代器并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!