jdk8-stream-并行流的使用

使用jdk的stream, 可以非常方便的将串行改为并行

1, 判断是否质数

    /**
     * 将一个stream改成简单的并行
     */
    @Test
    public void test1() {
        // 串行
        long count = IntStream.range(0, 100000).filter(this::isPrime).count();
        System.out.println(count);

        // 并行
        long count1 = IntStream.range(0, 100000).parallel().filter(this::isPrime).count();
        System.out.println(count1);
    }

    /**
     * 判断是否质数
     * @param num
     * @return
     */
    public Boolean isPrime(int num) {
        int tmp = num;
        if (tmp < 2) return false;
        for (int i = 2; Math.sqrt(tmp) >= i; i++) {
            if (tmp % i == 0) return false;
        }
        return true;
    }

可以看到, 调用了一个parallel() 就可以改为并行计算

2, 获取一个集合的并行流

 /**
     * 获取一个并行流
     */
    @Test
    public void test2() {
        List<JSONObject> objects = Lists.newArrayList();
        Stream<JSONObject> jsonObjectStream = objects.parallelStream();
    }

3, 使用并行排序

    /**
     * 并行排序
     */
    @Test
    public void test3() {
        int[] lists = new int[1000];
        Arrays.parallelSort(lists);
    }

猜你喜欢

转载自www.cnblogs.com/wenbronk/p/9100214.html