package com.frame.springboot;
import java.util.ArrayList;
import java.util.List;
public class Test {
static class Person {
private int age;
private String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
}
public static void main(String[] args) throws InterruptedException {
List<Person> list = new ArrayList<>(1000);
for (int i = 0; i < 1000; i++) {
Person person = new Person(i, String.valueOf(i));
list.add(person);
}
long startTime = System.currentTimeMillis();
//耗时26792ms
list.parallelStream().forEach((Person person) -> {
String name = person.name;
int age = person.age;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
//耗时109863ms
for (Person person : list) {
String name = person.name;
int age = person.age;
Thread.sleep(100);
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
}
话不多说看结果同样操作一个for循环,一个使用了并发流,一个串行运行。性能差了将近5倍。
如果去掉sleep的代码,那么并发流的性能反而还不如串行。但是如果其中的代码操作耗时,那么使用并发流是个不错的选择。