在Java-Stream流式编程中已经讲了流编程的使用方法,但是stream()是串行操作的。但是parallelStream()恰恰相反,是并行操作的,两者的执行效率的话肯定是parallelStream()要快,毕竟是多线程的,但是这就就会涉及到线程安全的问题了,一旦涉及到线程安全的问题,那些线程不安全的集合类型我们是一个都不能用的了,像什么HashMap,ArrayList,都不能用了,只能用线程安全的集合了。如果还纠结为什么线程不安全不能用或者为什么线程不安全的,可以去看下。里面有讲到哪些集合线程安全哪些不安全。
最后就看一下两者的执行效率跟parallelStream()使用线程不安全的集合会有什么后果呗
stream()+ 线程不安全的ArrayList
List<Integer> list = new ArrayList<>(100);
for(int i = 0;i<100;i++){
list.add(i);
}
List<Integer> testList = new ArrayList<>();
long startTime=System.currentTimeMillis(); //获取开始时间
list.stream().forEach(l->{
try {
Thread.sleep(1000);
testList.add(l);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
System.out.println(testList.size());
这个执行时间要命啊。
再看看parallelStream() + 线程不安全的ArrayList
List<Integer> list = new ArrayList<>(100);
for(int i = 0;i<100;i++){
list.add(i);
}
List<Integer> testList = new ArrayList<>();
long startTime=System.currentTimeMillis(); //获取开始时间
list.parallelStream().forEach(l->{
try {
Thread.sleep(1000);
testList.add(l);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
System.out.println(testList.size());
嘿快了这么多,不愧是并行的呀,可惜这个数据好像丢失了那么一丢丢。
最后正确的操作,parallelStream() + 线程安全的集合
List<Integer> list = new ArrayList<>(100);
for(int i = 0;i<100;i++){
list.add(i);
}
List<Integer> testList = Collections.synchronizedList(new ArrayList<>());
long startTime=System.currentTimeMillis(); //获取开始时间
list.parallelStream().forEach(l->{
try {
Thread.sleep(1000);
testList.add(l);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
System.out.println(testList.size());