定义一个测试类
public class TestParallelStream {
private List<Integer> list;
private int size;
private CountDownLatch countDownLatch;
@Before
public void initList(){
list = new ArrayList<>();
size = 100;
countDownLatch = new CountDownLatch(size);
for(int i=0; i<size; i++) {
list.add(i);
}
}
上面定义了一个100元素的list。
下面使用迭代器遍历:
/**
* 迭代器遍历
* @throws Exception
*/
@Test
public void testFor() throws Exception {
long start = System.currentTimeMillis();
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next());
}
System.out.println();
long end = System.currentTimeMillis();
System.out.println(end-start);
}
结果耗时稳定一位数的毫秒
使用parallelStream的方式:
/**
* 使用parallelSteam.forEach()遍历
* @throws Exception
*/
@Test
public void testListForEach() throws Exception{
long start = System.currentTimeMillis();
list.parallelStream().forEach(
l -> {
System.out.print(l);
countDownLatch.countDown();
}
);
countDownLatch.await();
System.out.println();
long end = System.currentTimeMillis();
System.out.println(end-start);
}
结果是稳定在50以上的两位数的毫秒。
但是当我们要进行耗时的操作时,比如说IO,这里用Thread.sleep(100)模拟IO。
用迭代器处理模拟的IO的方式:
/**
* 当有耗时操作时,使用迭代器遍历
* @throws Exception
*/
@Test
public void testForSleep() throws Exception {
long start = System.currentTimeMillis();
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next());
Thread.sleep(100);
}
System.out.println();
long end = System.currentTimeMillis();
System.out.println(end-start);
}
结果是比10000大一些的毫秒数。
用parallelStream处理模拟的IO:
/**
* 当有耗时操作时,使用parallelSteam.forEach()遍历
* @throws Exception
*/
@Test
public void testListParallelStream() throws Exception{
long start = System.currentTimeMillis();
list.parallelStream().forEach(
l -> {
System.out.print(l);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
}
);
countDownLatch.await();
System.out.println();
long end = System.currentTimeMillis();
System.out.println(end-start);
}
结果是比2500大一些的毫秒数。应该是跟我电脑4核有关,处理4个线程。是上面迭代器遍历时间的1/4.
总结
当数据量不大或者没有太耗时的操作时,顺序执行(如iterator)往往比并行执行更快,毕竟,分配资源、准备线程池和其它相关资源也是需要时间的;
当任务涉及到耗时操作(如I/O)并且任务之间不互相依赖时,那么并行化就是一个不错的选择。通常而言,将这类程序并行化之后,执行速度会提升好几个等级;
由于在并行环境中任务的执行顺序是不确定的,因此对于依赖于顺序的任务而言,并行化也许不能给出正确的结果。
参考:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架