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