2015-10-19 71 views
1

我在读J. Bloch的“Effective Java”,现在我在关于for-eachfor-loop的部分。他提到的三种情况,我们不能使用for-each环,其中之一是以下:L多个集合的并行迭代

并行迭代 - 如果你需要在 平行遍历多个集合,然后你在需要显式控制迭代器或索引 变量,以便所有迭代器或索引变量可以在 锁步中前进(如无意中在上面的示例中所示的buggy卡和骰子 中所示)。

这个案例对我来说不是很清楚,我无法想象一个例子。

我脑海中浮现的第一个想法是,它只是在多个线程中迭代相同的集合,但这可能不是他的意思。我没有看到任何限制阻止我们这样做(只读)。其实:

public class MyRunnable implements Runnable{ 

    private Collection<String> col; 

    //CTOR ommmited 

    public void run(){ 
    for(String s : col){ 
     //print o, not modify 
    } 

} 

然后我们只是用同一个实例启动一些线程。所以,我们并不害怕获得ConcurrentModificationExceptionJavaDocs),因为我们执行只读访问,即使是多线程同时执行也是如此。

怎么了?

回答

5

我不认为他同时表示“并行”。

它简单得多。假设你有两个集合,并且你需要相同的循环(不是嵌套循环)遍历它们,每个迭代中取每个集合的第i个元素。你不能用增强for循环来做到这一点,因为它隐藏了索引和迭代器。

您必须使用循环标准(有序​​集合):

private List<String> one; 
private List<String> two; 

public void run(){ 
    for(int i = 0; i<one.size() && i<two.size();i++){ 
     // do something with one.get(i) and two.get(i) 
    } 
} 

或明确的迭代器(对于非有序集合):

private Set<String> one; 
private Set<String> two; 

public void run(){ 
    for(Iterator<String> iterOne=one.iterator(),Iterator<String> iterTwo=two.iterator(); iterOne.hasNext()&&iterTwo.hasNext();){ 
     // do something with iterOne.next() and iterTwo.next() 
    } 
} 
+0

事实上,听起来很reasonbable。 –

+0

另请参阅https://stackoverflow.com/questions/1365793/how-to-most-elegantly-iterate-through-parallel-collections – JasonPlutext

1

并行iteration-如果您需要要并行运行 多个集合,则需要对迭代器或索引 变量进行显式控制,以便所有迭代器或索引变量都可以在 锁步(如无意中在上面的例子中的越野车卡和骰子 中示出的)。

用简单的英文lockstep表示同时。这意味着您无法使用for-each同时迭代多个集合。你将不得不使用不同的迭代器( 或循环如图叶兰)象下面这样:

Iterator iterator1 = list1.iterator(); 
Iterator iterator2 = list2.iterator(); 
Iterator iterator3 = list3.iterator(); 
while (iterator1 .hasNext() && iterator2 .hasNext() && iterator3.hasNext()){ 
    Item i1 = iterator1 .next(); 
    Item i2 = iterator2 .next(); 
    Item i3 = iterator3.next(); 
    // rest of your code. 
}