【发布时间】:2014-11-25 11:56:12
【问题描述】:
我正在为 400 行矩阵本身的矩阵乘法做一个编程类项目。我让它在顺序模式下工作,该项目的目标是编写一个并行实现。
我有以下代码,当然,当我尝试在内部类中引用计数器 j 时,我得到一个关于 j 必须如何“最终或有效最终”的错误。我发现这个解决方法使用最终数组但更改了第一个元素,但它给出了非常不可预测的结果,我原以为它会从 0 计数到 399,但它会以随机顺序吐出数字,然后复制很多数字,包括 399很多次。
有什么想法可以在内部类中使用递增的计数器吗?目标是调用该方法来处理内部类中矩阵中每一行的矩阵乘法,因为我们应该有与矩阵中的行一样多的线程。感谢您的帮助!
代码如下:
private static double parallelMatrixMultiply()
{
// use the existing arrays A and B, multiply them together
// use the parallel approach
// Create a fixed thread pool with maximum of three threads
ExecutorService executor = Executors.newFixedThreadPool(numRows);
final int[] counter = new int[]{0};
// submit a new thread for each row in the matrix
for (int j = 0; j < numRows ; j++)
{
// we can modify an element of an array that has been declared final
counter[0] = j;
// Submit runnable tasks to the executor
executor.execute(new Runnable() {
public void run()
{
// set a task to multiply for each row here
// will be replaced by a line to multiply each row of matrix
System.out.println(counter[0]);
}
});
}
// Shut down the executor
executor.shutdown();
// return the value of the 1,1 position on zero notation
//return matrixC.get(1).get(1); // return matrixC(1,1)
return 42.0;
}
【问题讨论】:
-
我搜索了,基于并行/线程找不到这个问题,很快就回去睡觉了,谢谢!
标签: java lambda parallel-processing