parallelStream().peek()的使用
public static void main(String[] args) throws ExecutionException, InterruptedException {
LinkedList<Map<Integer, Integer>> list =new LinkedList<>();
for (int i=1;i<10000;i++){
Map<Integer, Integer> map = new HashMap<>();
map.put(1,0);
list.add(map);
}
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(map ->{
map.put(1,2);
try {
//模拟业务耗时
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
缺点:
线程数量和CPU核数一致
需要等待线程全部执行完毕,主线程(调用线程)才继续往下执行
共享线程池,不能对不同任务分别设定线程池大小(其实真实业务也不需要)
//使用默认线程池的parallelStream
private static void Test2(LinkedList<Map<Integer, Integer>> list) {
list.parallelStream().peek(map ->{
map.put(1,2);
try {
//模拟业务耗时
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).collect(Collectors.toList());
}
//使用ForkJoinPool自定义线程池的parallelStream
private static void Test3(LinkedList<Map<Integer, Integer>> list) throws ExecutionException, InterruptedException {
ForkJoinPool pool = new ForkJoinPool(500);
pool.submit(() -> list.parallelStream().peek(map -> {
map.put(1,2);
try {
//模拟业务耗时
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).collect(Collectors.toList())).get();
}
该方式中,主进程(调用线程)不会等parallelStream流执行完毕。如需等待,使用future.get()方法阻塞;
我们创建自己的线程池,所以(1)可以避免共享线程池,(2)可以分配比处理机数量更多的线程