2014-12-02 103 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。另外,矩陣是隻有兩行而不是四行的二維數組。