2016-05-29 81 views
-3

我嘗試在這下面的代碼中使用線程間通信來計算兩個矩陣的乘法:什麼是錯在此代碼

 class matrix { 
    final static Integer lock = 0 ; 
    static int a[][] , b[][] ,result[][] ; 
    static int counter = 0 ; 
    public matrix(int[][] a , int[][] b) 
    { 
     counter = 0 ; 
     this.a = a ; 
     this.b = b ; 
     result = new int[a.length][b[0].length]; 
    } 


    public synchronized void calculate_a_coeff(int coefficient) 
    { 
     result[coefficient/a.length][coefficient%b[0].length] = 0 ; 
     for(int i = 0 ; i < a[0].length ; i++) 
     { 
      result[coefficient/a.length][coefficient%b[0].length] += a[coefficient/a.length][i]*b[i][coefficient%b[0].length] ; 
     } 
     counter++; 
     if(counter == a.length*b[0].length) 
      notifyAll() ; 
    } 

    public synchronized void showResult() 
    { 
     System.out.println("******show result*******"); 
     try{ 
      wait() ; 
     }catch(InterruptedException e) 
     { e.printStackTrace(); } 

     for (int i = 0 ; i < a.length ; i++) 
     {  for (int j = 0; j<b[0].length ; j++) 
       System.out.print(result[i][j]+"\t") ; 
     System.out.println() ; 
     } 
    } 
} 


public class Zmat { 
    public static void main(String args[]) 
    { 
     int[][] mat = new int[2][2] ; 
     mat[0][0]=mat[0][1]=mat[1][0]=mat[1][1]=1 ; 

     final matrix m = new matrix(mat,mat); 


     for(int i = 0 ; i < mat.length*mat[0].length ; i++) 
     {  
       int coefficient = i ; 
       new Thread(){ 
        public void run(){ 
          m.calculate_a_coeff(coefficient); 
         } 
        }.start(); 
     } 

     new Thread(){ 
      public void run(){ 
        m.showResult(); 
       } 
      }.start(); 
    } 
} 

當我運行這段代碼有時我有結果非常好:

******顯示結果*******

但有時我剛纔:

******顯示結果*******

與無限的運行

  • 你能告訴我什麼是錯誤的代碼?
  • 是否有任何其他版本來計算兩個矩陣的乘積?

預先感謝您..

回答

1

不完全知道爲什麼你在這裏使用線程。如果刪除了線程邏輯,它似乎在所有情況下運行都非常可靠。可能是某處的競賽狀況?