其他分享
首页 > 其他分享> > Stream的串行和并行

Stream的串行和并行

作者:互联网

sequential / parallel

sequential 返回的流是串行处理(默认就是,可以不写)

parallel返回的流是并行处理,参考如下测试用例:

@Test
    public void test12() throws Exception {
        IntStream intStream = IntStream.of(6, 1, 1, 2, 5, 2, 3, 4);
        long start=System.currentTimeMillis();
        //并行处理
        intStream.parallel().forEach(x->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":"+x);
        });
        System.out.println("parallel time->"+(System.currentTimeMillis()-start));
 
        intStream = IntStream.of(6, 1, 1, 2, 5, 2, 3, 4);
        start=System.currentTimeMillis();
        //默认都是串行处理
        intStream.sequential().forEach(x->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":"+x);
        });
        System.out.println("sequential time->"+(System.currentTimeMillis()-start));
    }

解决stream().parallel().forEach会返回空的问题

原因:1.parallelStream() - 为集合创建并行流;

           2.ArrayList是线程不安全的;

处理方法:

1、stream() − 为集合创建串行流;

2、Collections.synchronizedList(new ArrayList());
3、new CopyOnWriteArrayList<>()

举例:


public class ParallelTest {
    public static void main(String[] args) {
        //ArrayList<Object> arrayList = new ArrayList<>(); //List集合不安全,stream().parallel()操作不行,或返回空对象

        List<Object> arrayList = Collections.synchronizedList(new ArrayList<>());//解决方法一:集合工具类
        //CopyOnWriteArrayList<Object> arrayList = new CopyOnWriteArrayList<>(); //解决方法二:JUC的集合
        for (int i = 1; i <= 10; i++) {
            arrayList.add(String.valueOf(i));
        }
        System.out.println("新构建的集合"+arrayList);
        ArrayList<Object> result1 = new ArrayList<>();

        long start = System.currentTimeMillis();
        arrayList.stream().forEach((str)->{
            System.out.println(Thread.currentThread().getName()+",操作中。。。");
            result1.add(new User(2, (String) str,22));
        });
        System.out.println("使用串行流,修改集合"+result1);
        System.out.println("花费的时间为:"+(System.currentTimeMillis()-start));

        System.out.println("-------------------------------------");

        ArrayList<Object> result2 = new ArrayList<>();
        start = System.currentTimeMillis();
        arrayList.stream().parallel().forEach((str)->{
            System.out.println(Thread.currentThread().getName()+",操作中。。。");
            result2.add(new User(2, (String) str,22));
        });
        System.out.println("使用并行流,修改集合"+result2);
        System.out.println("花费的时间为:"+(System.currentTimeMillis()-start));

    }
}

标签:Stream,start,并行,System,currentTimeMillis,println,串行,new,out
来源: https://blog.csdn.net/qq_44507798/article/details/122515245