我想让我的代码更适合其他应用程序。
我没有代码问题,它完美无缺。我只想重写它以在其他环境中使用它。
我的原始代码:
import java.util.concurrent.*;
class Sum extends RecursiveTask<Double> {
final int seqThresHold = 500;
double[] data;
int start, end;
Sum(double[] vals, int s, int e ) {
data = vals;
start = s;
end = e;
}
protected Double compute() {
double sum = 0;
if((end - start) < seqThresHold) {
for(int i = start; i < end; i++) sum += data[i];
}
else {
int middle = (start + end) / 2;
Sum subTaskA = new Sum(data, start, middle);
Sum subTaskB = new Sum(data, middle, end);
subTaskA.fork();
subTaskB.fork();
sum = subTaskA.join() + subTaskB.join();
}
return sum;
}
}
class RecurTaskDemo {
public static void main(String args[]) {
ForkJoinPool fjp = new ForkJoinPool();
double[] nums = new double[5000];
for(int i=0; i < nums.length; i++)
nums[i] = (double) (((i%2) == 0) ? i : -i) ;
Sum task = new Sum(nums, 0, nums.length);
double summation = fjp.invoke(task);
System.out.println("Summation " + summation);
}
}
我想得到的新代码:
public class RecurTaskDemo {
private static double Sum(double[] data, int start, int end) {
double sum = 0;
for (int i = start; i < end; i++) {
sum += data[i];
}
return sum;
}
// ???
public static void main(String args[]) {
double[] nums = new double[4000];
for (int i = 0; i < nums.length; i++)
nums[i] = (double) (((i % 2) == 0) ? i : -i);
double sum = Sum(nums, 0, 4000);
// double sum = ... I would like to calculate 'sum' using 'Sum(...)' + '???'
System.out.println(sum);
}
}