要并行化子循环,必须首先了解每个子循环的结果。
第一个循环的结果是:
要计算它们,可以创建一个自定义类型来保存3个值,然后执行可变缩减来计算所有3个值。由于没有更好的名称,我将调用自定义类型
ResultContainer
是的。
类似地,第二个循环的结果是数组
a[i]
.这更简单,因为从
Stream
是的。
因此,这将给予:
for (int i0 = 1; i0 < x; i0++) {
final int i = i0; // tmp store as final for use in lambda
ResultContainer result = IntStream.range(0, y).parallel()
.collect(() -> new ResultContainer(y), (resultContainer, j) -> {
double a1 = a[i - 1][j];
double a2 = a[i][j];
double a3 = a1 * a2;
double cij = c[i - 1][j] + a3;
resultContainer.add(-a3, cij * a3, j, cij);
}, ResultContainer::add);
d += result.d;
e[i] = d + result.f;
c[i] = result.ci;
a[i] = IntStream.range(0, y).parallel().mapToDouble(j -> e[i] * b[i][j]).toArray();
}
根据我们的定制类型:
class ResultContainer {
double d;
double f;
double[] ci;
public ResultContainer(int y) {
this.d = 0;
this.f = 0;
ci = new double[y];
}
public void add(double d, double f, int j, double cij) {
this.d += d;
this.f += f;
ci[j] = cij;
}
public void add(ResultContainer resultContainer2) {
d += resultContainer2.d;
f += resultContainer2.f;
for (int j = 0; j < ci.length; j++) {
// note that one of the two is always 0 here
ci[j] += resultContainer2.ci[j];
}
}
}