这可能是非常基本的,但我不是 Java 人。这是我的处理代码,它只是打印和休眠:
private static void myProcessings(int value)
{
System.out.println("Processing " + value);
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Finished processing " + value);
}
现在,这个并行流似乎可以并行工作:
IntStream iit = IntStream.rangeClosed(1,3);
iit.parallel().forEach(Main::myProcessings);
// output:
// Processing 2
// Processing 1
// Processing 3
// Finished processing 3
// Finished processing 2
// Finished processing 1
但是这个(由迭代器制成)没有:
static class MyIter implements Iterator<Integer>
{
private int max;
private int current;
public MyIter(int maxVal)
{
max = maxVal;
current = 1;
}
@Override
public boolean hasNext()
{
return current <= max;
}
@Override
public Integer next()
{
return current++;
}
}
MyIter it = new MyIter(3);
StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, 0), true)
.forEach(Main::myProcessings);
// output:
// Processing 1
// Finished processing 1
// Processing 2
// Finished processing 2
// Processing 3
// Finished processing 3
我在自定义迭代器版本中做错了什么?(我正在使用 Java 8)