並行庫parallelStream設置並行數量


為什么要使用並行庫

在java中,我們通常使用並行庫,達到對多核處理器的最大利用,提高程序執行效率。在java8中,我們可以使用parallelStream來做一些並行處理。

    public static void main(String[] args) {
       testParalle();
    }

    private static void testParalle(){
        Stream<Integer> parallel = Arrays.asList(1, 2, 3, 5, 6, 7,8).stream().parallel();
        parallel.forEach(Application::doSome);
    }

    private static void doSome(int num) {
        try {
            System.out.println(String.format("time:%s begin:%s",LocalTime.now(),num));
            Thread.sleep(num * 500);
            System.out.println(String.format("time:%s end:%s",LocalTime.now(),num));
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

並行庫的底層

parallelStream默認使用了fork/join框架,其默認線程數是CPU核心數

觀察運行結果,可以發現只有4個並行,再次證實了該點(我的cpu是4核)

設置並行數

在某些場景中,我們不希望搶占所有的CPU核心。可以通過ForkJoinPool來設置並行數

public static void main(String[] args) {
      //testParalle();
      testParalleNum(2);
}
public static void testParalleNum(int parallelism) {
        Stream<Integer> stream = Arrays.asList(1, 2, 3, 5, 6, 7,8).stream();
        new ForkJoinPool(parallelism).submit(() -> stream.parallel().forEach(Application::doSome)).join();
    }

在這里,我們將並行數設置為2,可以看到結果:


免責聲明!

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



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