並行for循環

流式for循環

    private static void test1() {
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            arrayList.add(i + "");
        }
        arrayList.stream().forEach(e -> System.out.println(Thread.currentThread().getName() + " " + e));
    }

並行流式for循環

    private static void test2() {
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            arrayList.add(i + "");
        }
        arrayList.parallelStream().forEach(e -> System.out.println(Thread.currentThread().getName() + " " + e));
    }

forkjoin 並行流式for循環

    private static final ForkJoinPool pool = new ForkJoinPool(5);

    private static void test3() {
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            arrayList.add(i + "");
        }
        pool.submit(() -> arrayList.parallelStream().forEach(e -> {
            System.out.println(Thread.currentThread().getName() + " " + e);
        })).join();
    }

執行

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章