/* File: ThreadedMM.java Matrix multiplication in 4 threads. C = A x B One thread does the top left N/2 x N/2 portion of C Other thread do the top right, bottom left and bottom right. */ import java.util.* ; public class ThreadedMM { int N ; // the dimension int[][] A ; // the matrices int[][] B ; int[][] C ; // Just to call doThis public static void main (String [] args) { ThreadedMM obj = new ThreadedMM(2000) ; obj.doThis() ; } // Constructor. // Allocates memory for A, B and C. // Initializes A and B. // public ThreadedMM (int n) { N = n ; A = new int[N][N] ; B = new int[N][N] ; C = new int[N][N] ; // Random prg = new Random ( System.currentTimeMillis() ) ; Random prg = new Random ( 95762 ) ; // System.out.println("N = " + N) ; for (int i = 0 ; i < N ; i++ ) { for (int j = 0 ; j < N ; j++) { A[i][j] = prg.nextInt(N) ; B[i][j] = prg.nextInt(N) ; } } } // Actual "main program" // public void doThis () { doMult one, two, three, four ; // does the actual multiplication int half = N/2 ; // close enough to half // divyy up who does which corner of C[][] // one = new doMult(0, half, 0, half) ; two = new doMult(0, half, half+1, N-1) ; three = new doMult(half+1, N-1, 0, half) ; four = new doMult(half+1, N-1, half+1, N-1) ; Thread T1 = new Thread(one) ; Thread T2 = new Thread(two) ; Thread T3 = new Thread(three) ; Thread T4 = new Thread(four) ; T1.start() ; T2.start() ; T3.start() ; T4.start() ; try { T1.join() ; T2.join() ; T3.join() ; T4.join() ; } catch ( InterruptedException e ) { System.out.println("Oh look, an exception!") ; } /* // Print out C for debugging. // Skip this for big matrices. // for (int i = 0 ; i < N ; i++) { for (int j = 0 ; j < N ; j++) { System.out.print("[" + C[i][j] + "]") ; } System.out.println() ; } */ } // These objects do the actual multiplying // private class doMult implements Runnable { int beginRow, endRow ; int beginCol, endCol ; // Constructor remembers which rows of A and which columns of B // we want to multiply. // doMult(int rowStart, int rowStop, int colStart, int colStop) { beginRow = rowStart ; endRow = rowStop ; beginCol = colStart ; endCol = colStop ; } // When we start the thread the run method multiplies // rows of A with columns of B as determined by // beginRow, endRow, beginCol and endCol. // public void run() { // do the N^3 algorithm. int sum ; for (int i = beginRow ; i <= endRow ; i++) { for (int j = beginCol ; j <= endCol ; j++) { sum = 0 ; for (int k = 0 ; k < N ; k++) { sum += A[i][k] * B[k][j] ; } C[i][j] = sum ; } // end for j } // end for i } } }