001
002 import java.util.concurrent.Executors;
003 import java.util.concurrent.ExecutorService;
004 import java.util.concurrent.Future;
005 import java.util.concurrent.ExecutionException;
006
007
008 /**
009 * Parallel Matrix Multiplication using util.concurrent.
010 * Using dim(A) number of parallel tasks but given number of threads.
011 */
012
013 public class ConMult implements MMInf {
014
015 int anzahl = 1;
016
017 public ConMult(int threads) {
018 anzahl = threads;
019 }
020
021
022 /**
023 * Performs the multiplication of two matrices.
024 * C = A * B.
025 * @param C result matrix.
026 * @param A matrix.
027 * @param B matrix.
028 */
029 public void multiply(double[][] C, double[][] A, double[][] B) {
030 ExecutorService pool = Executors.newFixedThreadPool(anzahl);
031 Future[] f = new Future[A.length];
032 System.out.print("Starting " + A.length + " tasks ...");
033 for (int i=0; i < A.length; i++) {
034 f[i] = pool.submit( new ConRowMult(C,A,B,i) );
035 }
036 System.out.print(" started ...");
037 for (int i=0; i < A.length; i++) {
038 try {
039 f[i].get();
040 } catch (InterruptedException ignored) {
041 } catch (ExecutionException ignored) {
042 }
043 }
044 pool.shutdown();
045 System.out.println(" done ConMult");
046 }
047
048
049 public void multiplyDoesNotWork(double[][] C, double[][] A, double[][] B) {
050 ExecutorService pool = Executors.newFixedThreadPool(anzahl);
051 System.out.print("Starting " + A.length + " tasks ...");
052 for (int i=0; i < A.length; i++) {
053 pool.submit( new ConRowMult(C,A,B,i) );
054 }
055 System.out.print(" started ...");
056 pool.shutdown();
057 System.out.println(" done ConMult");
058 }
059
060 }
061
062
063 /**
064 * This class is derived from the class Thread.
065 * It performs a row multiplication.
066 */
067
068 class ConRowMult extends Thread {
069
070 double[][] A;
071 double[][] B;
072 double[][] C;
073 int i;
074
075 /**
076 * Constructor.
077 * @param Cp two dimensional result matrix.
078 * @param Ap two dimensional matrix.
079 * @param Bp two dimensional matrix.
080 */
081 ConRowMult(double[][] Cp, double[][] Ap, double[][] Bp, int ip) {
082 A = Ap; B = Bp; C = Cp; i = ip;
083 }
084
085 /**
086 * Runs the multiplication.
087 */
088 public void run() {
089 for (int j=0; j < B[0].length; j++) {
090 double c = 0.0;
091 for (int k=0; k < B.length; k++) {
092 c += A[i][k] * B[k][j];
093 }
094 C[i][j] = c;
095 }
096 }
097 }
098