Java 8使用布尔值打开parallel()流? [英] Java 8 turn on parallel() stream with boolean?

查看:204
本文介绍了Java 8使用布尔值打开parallel()流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何设计可以同时运行或单线程运行的方法。例如,我有一个像这样的方法:

I am wondering how I could design methods that could either be run concurrently or single threaded. For example I have a method like this:

/**
 * Produces the norm of the two vector {@code v1}.
 * 
 * @param v1
 *            The first vector.
 * 
 * @param v2
 *            The second vector
 * 
 * @throws MathException
 *             Of type {@code DIMENSION_MISMATCH} if
 *             {@code v1.getDimension()} is != {@code v2.getDimension()}.
 */
public static Function<Vector, Double> norm = (v) -> {
    return Math.sqrt(
            IntStream.range(0, v.getDimension()).mapToDouble(i -> Math.pow(v.getEntry(i), 2)).sum());
};

如果我想使嵌入流并行,那么我可以再次创建相同的方法并添加 parallel()到流但是增加了很多样板。是否有可以使用的 parallel(boolean)开关?

And if I want to make the embedded stream parallel then I could create the same method over again and add parallel() to the stream but that adds a lot of boilerplate. Is there a parallel(boolean) switch that can be used?

推荐答案

API本身没有这样的开关,但你可以很容易地自己添加:

There is no switch like this in the API itself but you can add it yourself quite easily:

public static Function<Vector, Double> getNorm(boolean parallel) {
    return v -> {
        IntStream stream = IntStream.range(0, v.getDimension());
        stream = parallel ? stream.parallel() : stream;
        return Math.sqrt(stream.mapToDouble(i -> Math.pow(v.getEntry(i), 2)).sum());
    };
};

此代码只需调用 parallel() 或不依赖于布尔参数。

This code simply calls parallel() or not depending on the boolean parameter.

这篇关于Java 8使用布尔值打开parallel()流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆