我正在编写一个使用线程来乘以两个矩阵的Java程序。我有以下代码:
public class MatrixMultiplication {
//Declare matrices
public static int[][] matrix1 = new int[][]{
{1,2,3,4},{3,2,1,4}
};
public static int[][] matrix2 = new int[][]{
{2,1,3,4},{4,2,5,3}
};
public static int[][] result = new int[4][4];
//Threads
public static Thread[][] threads = new Thread[4][4];
public static void main(String[] args){
//create worker threads with M and N hard-coded
for(int i = 0; i < threads.length; i++) {
for (int l = 0; l < threads[i].length; l++) {
threads[i][l] = new Thread(new Worker(matrix1, matrix2, result, i, l));
}
}
for(int i = 0; i < threads.length; i++){
for(int l = 0; l < threads[i].length; i++){
try {
threads[i][l].start();
threads[i][l].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("Contents of result matrix");
for(int i = 0; i < 4; i++)
for(int l = 0; l < 4; l++){
System.out.println("["+i+","+l+"] = "+result[i][l]);
}
}
}
class Worker implements Runnable{
int[][] m1;
int[][] m2;
int[][] result;
int row;
int col;
public Worker(int[][]m1, int[][] m2, int[][] result, int row, int col){
this.m1 = m1;
this.m2 = m2;
this.result = result;
this.row = row;
this.col = col;
}
public void run(){result[row][col] = (m1[row][col] * m2[col][col]) + (m1[row][col+1] * m2[col+1][col]);}
}
编程在多行,值得注意的行21和Worker线程类的run方法中抛出ArrayIndexOutOfBoundsException
。我尝试了几种变化无济于事,我正在寻找指导。非常感谢你。
答案 0 :(得分:0)
有几点问题。在第21行,您使用I+1
代替L+1
。此外,矩阵是二维数组,只有两行,而不是四行。