001    
002    /**
003     * Parallel Matrix Multiplication. 
004     * Using dim(A) number of threads.
005     * @author Heinz Kredel.
006     */
007    
008    public class ParMult implements MMInf {
009    
010    /**
011     * Performs the multiplication of two matrices.
012     * C = A * B.
013     * @param C result matrix.
014     * @param A matrix.
015     * @param B matrix.
016     */
017        public void multiply(double[][] C, double[][] A, double[][] B) {
018          Thread[] t = new Thread[A.length];
019          System.out.print("Starting " + A.length + " threads ...");
020          for (int i=0; i < A.length; i++) {
021              t[i] = new RowMult(C,A,B,i);
022              t[i].start();
023          }
024          System.out.print(" started ...");
025          for (int i=0; i < A.length; i++) {
026              try { t[i].join(); }
027              catch (InterruptedException e) { }
028          }
029          System.out.println(" done ParMult");
030        }
031    
032    }
033    
034    
035    /**
036     * This class is derived from the class Thread.
037     * It performs a row multiplication.
038     */
039    class RowMult extends Thread {
040    
041        double[][] A;
042        double[][] B;
043        double[][] C;
044        int i;  
045    
046    /**
047     * Constructor.
048     * @param Cp Two dimensional Matrices.
049     * @param Ap Two dimensional Matrices.
050     * @param Bp Two dimensional Matrices.
051     */
052      RowMult(double[][] Cp, double[][] Ap, double[][] Bp, int ip) {
053        A = Ap; B = Bp; C = Cp; i = ip;
054      }
055    
056    /**
057     * Runs the multiplication.
058     */
059      public void run() {
060        for (int j=0; j < B[0].length; j++) {
061          double c = 0.0;
062          for (int k=0; k < B.length; k++) {
063              c += A[i][k] * B[k][j];
064          }
065          C[i][j] = c;
066        }
067      }
068    }
069