Stream多线程并行数据处理
将一个顺序执行的流转变成一个并发的流只要调用 parallel()方法
parallel()和sequential()可以调用多次。
/**
* 将当前流转为并行流
*/
S parallel();
/**
* 将当前流转为顺序流
*/
S sequential();
并行流
//.parallelStream()
List<Integer> integerList= new ArrayList<>();
List<String> stringList= Collections.synchronizedList(new ArrayList<>());
int sec = 999999;
for(int i = 0; i<sec; i++) {
integerList.add(new Random().nextInt(sec));
}
// 并行流将integerList转成stringList
integerList.parallelStream().forEach(i -> stringList.add(i.toString()));
并行流有线程安全问题,因此流中有线程不安全的集合(new ArrayList<>())进行添加/删除操作时要加Collections.synchronizedList(target)修饰。