我正在尝试理解reduce方法。如果我使用stream()和reduce一起使用,那么我会得到_ab
,但是如果我使用parallelStream()
和reduce一起使用,我会得到_a_b
。难道不应该无论我们使用parallelStream还是stream,reduce的输出都应该是相同的吗?
import java.util.*;
import java.util.stream.*;
class TestParallelStream{
public static void main(String args[]){
List<String> l = Arrays.asList("a","b","c","d");
String join=l.stream()
.peek(TestParallelStream::sleepFor)
.reduce("_",(a,b) -> a.concat(b));
System.out.println(join);
}
public static void sleepFor(String w){
System.out.println("inside thread:"+w);
try{
Thread.currentThread().sleep(5000);
}catch(InterruptedException e){ }
}
}