我需要一个更简单的问题来解决。我需要解决 1000 个随机 X 值和 1000 个随机 Y 值的并行求和。我正在使用java的Parallel ForkJoin框架。使用单一计算方法,不可能计算完全不同路径中 X 值和 Y 值的总和。
此外,我需要计算 X * Y 的总和。即单个线程遍历的 Σxiyi BUT X 值分配一个单独的任务,并且 Y 作为单独的任务插入到线程池中。那么如何同时乘以 X 和 Y 值,即 X * Y ==> (X = 100, Y = 150)?第一个线程在 X 上运行,第二个在 Y 上运行。
代码:
公共类 RegressionLineForkJoin {
//private static final ForkJoinPool forkJoinPool = new ForkJoinPool( 2 ); // use only 2 processors
private static Random r = new Random( );
private static final int NR_OF_VALUES = 1000; // X & Y VALUES
private static final int THRESHOLD = 100; // need to calculate Threshold value.
private static class RegressionLineForkJoinTask extends RecursiveTask<Integer>
{
private int m_Start;
private int m_End;
public RegressionLineForkJoinTask(int a_start,int a_end)
{
this.m_Start = a_start;
this.m_End = a_end;
}
public Integer compute()
{
Integer Sum = 0;
if(this.m_End - this.m_Start < THRESHOLD)
{
calculateSum(this.m_Start,this.m_End);
}
else
{
int split = (this.m_Start + this.m_End)/2;
RegressionLineForkJoinTask oRegressionLineTask_1 = new RegressionLineForkJoinTask(this.m_Start , split);
RegressionLineForkJoinTask oRegressionLineTask_2 = new RegressionLineForkJoinTask( split+1 , this.m_End);
// Invoke the tasks in parallel
invokeAll(oRegressionLineTask_1,oRegressionLineTask_2);
Sum += oRegressionLineTask_1.join();
Sum += oRegressionLineTask_2.join();
//Sum
}//end of else
return Sum;
}
public static void main(String[ ] args)
{
RegressionLineForkJoinTask oRegressionLineForkJoinTask_X = new RegressionLineForkJoinTask( 0,NR_OF_VALUES );
RegressionLineForkJoinTask oRegressionLineForkJoinTask_Y = new RegressionLineForkJoinTask( 0,NR_OF_VALUES );
Integer Sum_X_Values = forkJoinPool.invoke(oRegressionLineForkJoinTask_X);
Integer Sum_Y_Values = forkJoinPool.invoke(oRegressionLineForkJoinTask_Y);
System.out.println("in main after forkjoin.invoke()");
}
private static double nextRandomFunctionValue(int a_startInex,int a_endIndex)
{
double randomValue = 0.0;
randomValue = a_startInex + ( a_endIndex - a_startInex ) * r.nextDouble( );
return randomValue;
}//end of nextRandomFunctionValue
private static double calculateSum(int a_startIndex, int a_endIndex)
{
double sumValue = 0.0;
double RandomeValue = 0.0;
for(int index = a_startIndex; index< a_endIndex; index++)
{
RandomeValue = nextRandomFunctionValue(a_startIndex,a_endIndex);
sumValue += RandomeValue;
}//end of for
return sumValue;
}
}
}