@Test
public void testStream(){
Object lock = new Object();
ArrayList<Integer> collect = Arrays.asList(1, 2, 3, 4, 5)
.parallelStream() //并行流
.collect(() -> { //构造器参数
synchronized (lock) { //加锁是为了并行流下方便查看打印结果
System.out.println("constructor:Thread:" + Thread.currentThread());
System.out.println(); //为了换行方便查看打印
return new ArrayList<Integer>();
}
}, (a, b) -> { //累加参数
synchronized (lock) { //加锁是为了并行流下方便查看打印结果
System.out.println("accumulator:Thread:" + Thread.currentThread());
System.out.println("a:" + a);
System.out.println("b:" + b);
System.out.println(); //为了换行方便查看打印
a.add(b);
}
}, (a, b) -> { //合并参数
synchronized (lock) { //加锁是为了并行流下方便查看打印结果
System.out.println("combiner->a:length:" + a.size() + " " + "b:length:" + b.size());
System.out.println("a:" + a + ",b:" + b);
a.addAll(b);
System.out.println(); //为了换行方便查看打印
}
});
//.forEach(item -> System.out.println("Thread:" + Thread.currentThread() + " All:" + item));
System.out.println("all:"+collect);
}
|