这段代码有什么问题

时间:2016-05-29 15:54:47

标签: java

我尝试使用以下代码来计算使用线程间通信的两个矩阵的乘法:

     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(); 
     }
 }

当我运行此代码时,我的结果非常好:

******显示结果*******

2 2
2 2

但有时我只是:

******显示结果*******

无限运行

  • 你能告诉我这段代码有什么不对吗?
  • 有没有其他版本来计算两个矩阵的乘积?

提前谢谢..

1 个答案:

答案 0 :(得分:1)

不完全确定你在这里使用线程的原因。如果删除线程逻辑,它似乎在所有情况下都非常可靠地运行。可能是某个地方的竞争条件?