测试一
public class SteamTest {
public static void main(String[] args) {
List<String> list1 = new Random().ints().limit(100).mapToObj(i -> "asdd"+i).distinct().collect(Collectors.toList());
SteamTest test = new SteamTest();
test.Test1(list1);
test.Test2(list1);
}
public void Test1(List<String> list1){
Map<String,Object> str = new HashMap();
Long time = System.currentTimeMillis();
list1.parallelStream().forEach(s -> {
str.put(s,getString(s));
});
System.out.println("parallelStream运行结束,耗时:"+(System.currentTimeMillis()-time));
System.out.println(str.keySet().size());
}
public void Test2(List<String> list1){
Map<String,Object> str = new HashMap();
Long time = System.currentTimeMillis();
list1.stream().forEach(s -> {
str.put(s,getString(s));
});
System.out.println("stream运行结束,耗时:"+(System.currentTimeMillis()-time));
System.out.println(str.keySet().size());
}
public String getString(String str){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return str+"str";
}
}
//结果
//parallelStream运行结束,耗时:1414
//86
//stream运行结束,耗时:10053
//100
测试二
public void Test1(List<String> list1){
Map<String,Object> str = new HashMap();
Long time = System.currentTimeMillis();
list1.parallelStream().forEach(System.out::println);
System.out.println("parallelStream运行结束,耗时:"+(System.currentTimeMillis()-time));
}
public void Test2(List<String> list1){
Map<String,Object> str = new HashMap();
Long time = System.currentTimeMillis();
list1.stream().forEach(System.out::println);
System.out.println("stream运行结束,耗时:"+(System.currentTimeMillis()-time));
}
//结果
//parallelStream运行结束,耗时:9
//stream运行结束,耗时:3
测试3
public void Test1(List<String> list1){
Map<String,Object> str = new HashMap();
Long time = System.currentTimeMillis();
list1.parallelStream().forEach(s -> {
sleepTest(1);
});
System.out.println("parallelStream运行结束,耗时:"+(System.currentTimeMillis()-time));
}
public void Test2(List<String> list1){
Map<String,Object> str = new HashMap();
Long time = System.currentTimeMillis();
list1.stream().forEach(s -> {
sleepTest(2);
});
System.out.println("stream运行结束,耗时:"+(System.currentTimeMillis()-time));
}
public String getString(String str){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return str+"str";
}
public void sleepTest(int i){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
//1输出100次
//parallelStream运行结束,耗时:1315
//2输出100次
//stream运行结束,耗时:10055
1.parallelStream 并行流 线程不安全 数据丢失 执行耗时业务速度大于steam
2.stream 串行流 线程安全 数据不会丢失 执行耗时业务速度慢 非耗时业务速度大于parallelStream
纯记录