我想知道如何设计可以并发运行或单线程运行的方法。例如我有一个这样的方法:
/**
* 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)
可以使用什么开关?
最佳答案
API 本身没有这样的开关,但您可以很容易地自己添加它:
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()
或不取决于 boolean 参数。
关于Java 8 使用 boolean 值打开并行()流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34639249/