Given:
class Sum extends RecursiveAction { //line n1
static final int THRESHOLD_SIZE = 3;
int stIndex, lstIndex;
int[] data;
public Sum(int[] data, int start, int end) {
this.data = data;
this.stIndex = start;
this.lstIndex = end;
}
protected void compute() {
int sum = 0;
if (lstIndex - stIndex <= THRESHOLD_SIZE) {
for (int i = stIndex; i < lstIndex; i++) {
sum += data[i];
}
System.out.println(sum);
} else {
new Sum(data, stIndex + THRESHOLD_SIZE, lstIndex).fork();
new Sum(data, stIndex,
Math.min(lstIndex, stIndex + THRESHOLD_SIZE)
).compute();
}
}
}
and the code fragment:
ForkJoinPool fjPool = new ForkJoinPool();
int data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
fjPool.invoke(new Sum(data, 0, data.length));
and given that the sum of all integers from 1 to 10 is 55.
Which statement is true?
A. The program prints several values that total 55.
B. The program prints 55.
C. A compilation error occurs at line n1.
D. The program prints several values whose sum exceeds 55.
题解
ForkJoinPool 可以将一个大问题拆成很多小问题来进行运算。而 RecursiveAction 是一种 ForkJoinTask,没有回传值。
在这个题目中,要利用 ForkJoinPool 和 RecursiveAction 来进行整数数组的元素加总计算。
调用 ForkJoinPool 对象的 invoke 方法后,会运行 RecursiveAction 的 compute 方法,此时 stIndex=0、lstIndex=10。程序第 15 行的判断式不成立,会再 fork 出新的 Sum 对象,用新的线程来计算「stIndex=3、lstIndex=10」的部份,而目前的线程则重新计算「stIndex=0、lstIndex=3」的部份。
「stIndex=0、lstIndex=3」,会计算 sum=1+2+3=6,输出「6」。
「stIndex=3、lstIndex=10」,会再 fork 出「stIndex=6、lstIndex=10」,计算「stIndex=3、lstIndex=6」的 sum 为 4+5+6=15,输出「15」。
「stIndex=6、lstIndex=10」,会再 fork 出「stIndex=9、lstIndex=10」,计算「stIndex=6、lstIndex=9」的 sum 为 7+8+9=24,输出「24」。
「stIndex=9、lstIndex=10」,会计算 sum=10,输出「10」。
以上输出由于是在不同线程处理的关系,所以顺序不是固定的,但这些输出的值加总后,即为 1 加到 10 的总和「55」。所以答案是选项 A。
