版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_33625560/article/details/83994707
并行流是一个把内容分成多个数据块的,并用不同的线程分别处理每个数据块的流。下面通过简单的示例介绍一下顺序流和并行流的特点。后面后时间在详细记录。
并行流:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for(int i =0;i<10;i++){
list.add(String.valueOf(i));
}
list.parallelStream().forEach(l ->{
try {
Thread.sleep(1000);
System.out.println(l+" "+DateUtil.now());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
输出结果:
8 2018-11-12 16:51:43
4 2018-11-12 16:51:43
0 2018-11-12 16:51:43
1 2018-11-12 16:51:43
6 2018-11-12 16:51:43
9 2018-11-12 16:51:43
7 2018-11-12 16:51:43
2 2018-11-12 16:51:43
5 2018-11-12 16:51:44
3 2018-11-12 16:51:44
顺序流:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for(int i =0;i<10;i++){
list.add(String.valueOf(i));
}
list.stream().forEach(l ->{
try {
Thread.sleep(1000);
System.out.println(l+" "+DateUtil.now());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
输出接口:
在这里插入代码片
0 2018-11-12 16:52:36
1 2018-11-12 16:52:37
2 2018-11-12 16:52:38
3 2018-11-12 16:52:39
4 2018-11-12 16:52:40
5 2018-11-12 16:52:41
6 2018-11-12 16:52:42
7 2018-11-12 16:52:43
8 2018-11-12 16:52:44
9 2018-11-12 16:52:45
分析:
可以看到并行流和顺序流的区别只是parallelStream和stream的区别,并行流的线程数默认取决于处理器的数量,这个值是有Runtime.getRuntime().available-Processors()得到的,可以修改(不推荐),他的原理是通过java7开始有的分支/并行框架(fock/join)就是讲一个大的任务不断的递归拆分知道可以执行。当然并行流也不可以乱用,否则效率可能还不如顺序流。