2014-12-02 57 views
-1

我正在编写一个使用线程来乘以两个矩阵的Java程序。我有以下代码: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]);} 
} 

编程在多个行抛出ArrayIndexOutOfBoundsException,值得注意线21,并在工作线程类的run方法。我尝试了几个变化无济于事,正在寻找这方面的指导。非常感谢你。

+1

如果您阻止每个线程的执行直到它终止,那么多线程的意义何在? – 2014-12-02 19:56:36

+1

你尝试了几个变化,但你显然没有一步步通过。您使用col + 1作为矩阵的索引。看看col会采取什么样的值。 – Fildor 2014-12-02 20:15:06

回答

0

存在几个问题。在第21行,您使用I+1而不是L+1。另外,矩阵是只有两行而不是四行的二维数组。