stream 并行操作

如果要使stream中的操作并行,使用起来非常简单,只要加parallel()就可以了

    public static void main(String[] args) throws Exception {
        /**
         * 并行操作:parallel()
         * 顺序操作:sequential()
         */
        Optional<Integer> max = Stream.iterate(1, x -> x + 1).limit(20000).parallel().peek(x -> {
            System.out.println(Thread.currentThread().getName());
        }).max(Integer::compare);
        System.out.println(max.get());
    }

反之如果,想要让并行转换为串行也只要加sequential()

    public static void main(String[] args) throws Exception {
        /**
         * 并行操作:parallel()
         * 顺序操作:sequential()
         */
        Optional<Integer> max = Stream.iterate(1, x -> x + 1).limit(20000).parallel().sequential().peek(x -> {
            System.out.println(Thread.currentThread().getName());
        }).max(Integer::compare);
        System.out.println(max.get());
    }

sequential()和parallel()的前后位置决定了最后谁生效,最后一个声明会生效.

此外,stream api流用的线程池是

ForkJoinPool.commonPool()

内部默认核心线程数量是cpu的核心数

/**
     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
     * java.lang.Runtime#availableProcessors}, using the {@linkplain
     * #defaultForkJoinWorkerThreadFactory default thread factory},
     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
     *
     * @throws SecurityException if a security manager exists and
     *         the caller is not permitted to modify threads
     *         because it does not hold {@link
     *         java.lang.RuntimePermission}{@code ("modifyThread")}
     */
    public ForkJoinPool() {
        this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
             defaultForkJoinWorkerThreadFactory, null, false);
    }

如果需要手动执行线程数的话可以使用

//设置为5个线程加上主线程就是6个线程在同时执行
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","5");

当然也可以在java程序启动时,给定参数

-D java.util.concurrent.ForkJoinPool.common.parallelism=5
也可以达到相同的效果

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • about Stream 什么是流? Stream是java8中新增加的一个特性,被java猿统称为流. Stre...
    jsondream阅读 25,376评论 8 47
  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 3,977评论 2 8
  • 本文采用实例驱动的方式,对JAVA8的stream API进行一个深入的介绍。虽然JAVA8中的stream AP...
    浮梁翁阅读 25,899评论 3 50
  • 世界杯万元奖金征文大赛——活动详情请点击:活动传送门 俄罗斯世界杯小组赛首轮最后一个比赛日,最后出场的亚洲球队日本...
    罗跑客阅读 441评论 0 0
  • 数着夜半的星晴, 享受着吱吱的虫鸣, 风带着大山的味道来到我身前, 雾缓缓出现在大山的身边, 一会我离大山很近, ...
    见十二阅读 200评论 0 1