33import org .apache .commons .collections4 .ListUtils ;
44
55import java .util .List ;
6+ import java .util .function .Supplier ;
67import java .util .stream .Collectors ;
78import java .util .stream .IntStream ;
89
910/**
1011 * @author vector
1112 * @date: 2018/10/18 0018 10:00
12- *
13+ * <p>
1314 * List<List<?>> -> List<?>
14- *
15+ * <p>
1516 * 使用parallelstream需注意【共享对象的可变状态】
1617 * 如使用foreach就能改变其状态
1718 * 需要特别注意下
1819 */
1920public class StreamParallellTest {
2021
21- public static List <String > sum (List <Integer > items ,int count ) {
22+ public static List <String > sum (List <Integer > items , int count ) {
2223 List <List <Integer >> listList = ListUtils .partition (items , count );
2324 return listList .stream ().flatMap (List ::stream ).map (StreamParallellTest ::delayFun ).collect (Collectors .toList ());
2425 }
2526
26- public static List <String > parallelSum (List <Integer > items ,int count ) {
27+ public static List <String > parallelSum (List <Integer > items , int count ) {
2728 List <List <Integer >> listList = ListUtils .partition (items , count );
2829 return listList .parallelStream ().flatMap (List ::stream ).map (StreamParallellTest ::delayFun ).collect (Collectors .toList ());
2930 }
@@ -37,26 +38,20 @@ public static String delayFun(int digist) {
3738 return digist + "" ;
3839 }
3940
41+ private static void execute (String msg , Supplier <List <String >> supplier ) {
42+ long s = System .nanoTime ();
43+ supplier .get ();
44+ long e = System .nanoTime ();
45+ long duration = (e - s ) / 1_000_000 ;
46+
47+ System .out .println (msg + " done in " + duration + " msecs" );
48+ }
49+
50+
4051 public static void main (String [] args ) {
4152 List <Integer > items = IntStream .rangeClosed (1 , 50 ).boxed ().collect (Collectors .toList ());
4253 System .out .println (items );
43- long s = System .currentTimeMillis ();
44- sum (items ,10 );
45- long e = System .currentTimeMillis ();
46- System .out .println ((double )(e -s )/1_000 + "s" );
47-
48- long s1 = System .currentTimeMillis ();
49- parallelSum (items ,10 );
50- long e1 = System .currentTimeMillis ();
51- System .out .println ((double )(e1 -s1 )/1_000 + "s" );
52- // for (int i = 0; i < 10; i++) {
53- // for (int j = 0; j < 10; j++) {
54- // long s1 = System.currentTimeMillis();
55- // parallelSum(items,10);
56- // long e1 = System.currentTimeMillis();
57- // System.out.println((double)(e1-s1)/1_000 + "s");
58- // }
59- // System.out.println("============================");
60- // }
54+ execute ("sum" , () -> sum (items , 10 ));
55+ execute ("parallelSum" , () -> parallelSum (items , 10 ));
6156 }
6257}
0 commit comments