1.前言
日常工作中,我们大部分代码都是串行化运行的,在目前主流的springboot还是ssm中,一个请求一般对应一个线程去处理,假设这个接口处理的业务量比较大时,会导致响应特别慢,这时候我们可以使用并行的思想去优化代码,即在串行化代码块中,将大量业务的处理交给多个线程去处理,提高运行效率。
2.主角parallelStream
parallelStream提供了流的并行处理,它是Stream的另一重要特性,其底层使用Fork/Join框架实现。简单理解就是多线程异步任务的一种实现,适合无返回值的数据处理场景
3.parallelStream如何使用
public class TestParallelStream {
public static void main(String[] args) throws ExecutionException, InterruptedException {
LinkedList<Map<Integer,Integer>> list = new LinkedList<>();
//模拟业务量
for (int i=1;i<300;i++){
Map<Integer,Integer> a = new HashMap<>();
a.put(1,0);
list.add(a);
}
long time1 = System.currentTimeMillis();
Test1(list);
long time2 = System.currentTimeMillis();
System.out.println("Test1耗时:"+(time2 - time1));
Test2(list);
long time3 = System.currentTimeMillis();
System.out.println("Test2耗时:"+(time3 - time2));
Test3(list);
long time4 = System.currentTimeMillis();
System.out.println("Test3耗时:"+(time4 - time3));
}
//单线程处理
private static void Test1(LinkedList<Map<Integer,Integer>> list){
list.forEach(i ->{
i.put(1,2);
try {
//模拟业务耗时
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// System.out.println(JSON.toJSONString(collect));
}
//使用默认线程池的parallelStream
private static void Test2(LinkedList<Map<Integer,Integer>> list){
List<Map<Integer, Integer>> collect = list.parallelStream().peek(i -> {
i.put(1, 2);
try {
//模拟业务耗时
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).collect(Collectors.toList());
// System.out.println(JSON.toJSONString(collect));
}
//使用ForkJoinPool自定义线程池的parallelStream
private static void Test3(LinkedList<Map<Integer,Integer>> list) throws ExecutionException, InterruptedException {
ForkJoinPool customThreadPool = new ForkJoinPool(500);
List<Map<Integer, Integer>> maps = customThreadPool.submit(() -> list.parallelStream().peek(i -> {
i.put(1, 2);
try {
//模拟业务耗时
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).collect(Collectors.toList())).get();
// System.out.println(JSON.toJSONString(maps));
}
}
4.代码运行结果
Test1耗时:352
Test2耗时:88
Test3耗时:22
5.总结
从结果看,parallelStream的效率远大于单线程的,因为是多线程并行处理效率高,parallelStream默认使用的线程池线程数是CPU核心数(所以线程数比较少),如果使用自定义线程池修改其线程核心数则可以达到更高的效率。