【java多线程】java8的流操作api和fork/join框架

一、测试一个案例,说明java8的流操作是并行操作

1、代码

package com.spring.test.service.forkjoin;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 */
public class Java8Test {


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

    public static void testList(){
        //源数据
        List<Integer> integerList=new ArrayList<>();
        integerList.add(0);
        integerList.add(1);
        integerList.add(2);
        integerList.add(3);
        integerList.add(4);
        integerList.add(5);
        integerList.add(6);
        integerList.add(7);
        integerList.add(8);
        integerList.add(9);

        //java的顺序操作
        for(Integer a:integerList){
            System.out.println(Thread.currentThread().getName()+"==>"+a);
        }


        //java的并行操作
        integerList.parallelStream().forEach(integer -> {
            System.out.println(Thread.currentThread().getName()+"==>"+integer);
        });


    }
}
View Code

2、执行结果

main==>0
main==>1
main==>2
main==>3
main==>4
main==>5
main==>6
main==>7
main==>8
main==>9
main==>6
main==>5
ForkJoinPool.commonPool-worker-4==>7
ForkJoinPool.commonPool-worker-1==>2
ForkJoinPool.commonPool-worker-4==>9
ForkJoinPool.commonPool-worker-2==>8
ForkJoinPool.commonPool-worker-4==>0
ForkJoinPool.commonPool-worker-3==>1
ForkJoinPool.commonPool-worker-5==>4
ForkJoinPool.commonPool-worker-1==>3
View Code

猜你喜欢

转载自www.cnblogs.com/shangxiaofei/p/10584982.html