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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM