| 集合做重复的操作,如果使⽤串⾏执⾏会相当耗时,因此⼀般会采⽤多线程来加快, Java8的paralleStream⽤fork/join框架提供了并发执⾏能⼒ |
| 底层原理 |
| 线程池(ForkJoinPool)维护⼀个线程队列 |
| 可以分割任务,将⽗任务拆分成⼦任务,完全贴合分治思想 |
| public class Main { |
| |
| public static void main(String[] args) throws Exception { |
| |
| List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9); |
| numbers.stream().forEach(System.out::println); |
| numbers.parallelStream().forEach(System.out::println); |
| } |
| |
| } |
- paralleStream并⾏是否⼀定⽐Stream串⾏快?
| 错误,数据量少的情况,可能串⾏更快,ForkJoin会耗性能 |
| 不⾏,部分情况会有线程安全问题,parallelStream⾥⾯使⽤的外部变量,⽐如集合⼀定要使⽤线程安全集合,不然就会引发多线程安全问题 |
| public class Main { |
| |
| public static void main(String[] args) throws Exception { |
| for(int i=0;i<10;i++){ |
| |
| List list = new CopyOnWriteArrayList(); |
| IntStream.range(0,100).parallel().forEach(list::add); |
| System.out.println(list.size()); |
| } |
| } |
| |
| } |
| public class Main { |
| |
| public static void main(String[] args) throws Exception { |
| |
| int value = Stream.of(1, 2, 3, 4, 5).reduce((item1, item2) -> item1 + item2).get(); |
| System.out.println(value); |
| |
| |
| int value = Stream.of(1, 2, 3, 4, 5).reduce(new BinaryOperator<Integer>() { |
| @Override |
| public Integer apply(Integer integer, Integer integer2) { |
| return integer+integer2; |
| } |
| }).get(); |
| System.out.println(value); |
| |
| |
| int value = Stream.of(1, 2, 3, 4, 5).reduce(100,(item1,item2)->item1+item2); |
| System.out.println(value); |
| |
| |
| int value = Stream.of(1645, 234345, 32, 44434, 564534, 435, 34343542, 212) |
| .reduce((item1, item2) -> item1 > item2 ? item1 : item2).get(); |
| System.out.println(value); |
| } |
| |
| } |
| public class Main { |
| |
| public static void main(String[] args) throws Exception { |
| |
| List<String> list = Arrays.asList("sdfsdf","xxxx","bbb"); |
| |
| list.forEach(obj->System.out.println(obj)); |
| |
| list.forEach(System.out::println); |
| }); |
| |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术