美文网首页
JAVA8 parallelStream 番外篇

JAVA8 parallelStream 番外篇

作者: _大叔_ | 来源:发表于2020-06-09 11:28 被阅读0次

多个不同线程 同时执行 parallelStream操作,会阻塞嘛?

首先单线程如果多处使用 parallelStream 一定会阻塞,他会等把一个流里得数据处理完毕,才会进行下一个 parallelStream 操作。

    public static void main(String[] args) {

        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","2");

        new Thread(() -> {
            System.out.println("运行阻塞");
            Arrays.stream(new int[]{1,2,3,4,5,6}).parallel().map(i -> aa(i)).forEach(System.out::println);
        }).start();

        new Thread(() -> {
            System.out.println("运行非阻塞");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Arrays.stream(new int[]{8,9,10,11,12,13}).parallel().forEach(System.out::println);
        }).start();

    }

    public static int aa(int i){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return i;
    }

结果:
运行阻塞
运行非阻塞
11
13
12
9
10
8
1
4
2
6
5
3

多线程不会阻塞,也就是说他们不会公用同一个线程池。

如何让他们公用同一个线程池?

    public static void main(String[] args) throws InterruptedException {
        ForkJoinPool pool = new ForkJoinPool(2);

        new Thread(() -> {
            System.out.println("运行阻塞");
            pool.execute(() -> {
                Arrays.stream(new int[]{1,2,3,4,5,6}).parallel().map(i -> aa(i)).forEach(System.out::println);
            });
        }).start();

        new Thread(() -> {
            System.out.println("运行非阻塞");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            pool.execute(() -> {
                Arrays.stream(new int[]{8,9,10,11,12,13}).parallel().forEach(System.out::println);
            });
        }).start();
//        pool.shutdown();
        Thread.sleep(500000);
    }

    public static int aa(int i){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return i;
    }
结果:
运行阻塞
运行非阻塞
2
4
6
3
5
1
11
13
12
8
10
9

我们可以在项目里封装一个方法让线程池让公用,当然数据量小的话,不用公用线程池也没什么问题了。

相关文章

网友评论

      本文标题:JAVA8 parallelStream 番外篇

      本文链接:https://www.haomeiwen.com/subject/ujkstktx.html