0

我想让我的代码对其他应用程序更易于实现。

我的代码没有问题,它工作得很好。我只想重写它以在其他情况下使用它。

我的原始代码:

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);

    }

}
4

0 回答 0