zoukankan      html  css  js  c++  java
  • 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);
        }
  • 相关阅读:
    实验6 继承
    实验5 运算符重载
    实验4 类初步
    实验3 文件操作
    实验2 C++数组与指针
    实验1 C++函数
    C++程序设计实验安排
    计算机图形学课件pdf版
    《三维建模简介》课件
    《3D建模初步》参考资料
  • 原文地址:https://www.cnblogs.com/wenbronk/p/9100214.html
Copyright © 2011-2022 走看看