package example.matmul;

import android.app.Activity;
import android.os.Bundle;

public class MatMulActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      double a[][] = {{1, 2, 3}, {4, 5, 6}};
      double b[][] = { {1, -1}, {-1, 1}, {1, 1} };
      final  int numRows = a.length;
      final  int numCols = b[0].length;
      final  int nThreads = numRows * numCols;
      double c[][] = new double[numRows][numCols];
      int k = 0;

      System.out.println ("Matrix a: ");
      printMat ( a );
      System.out.println ("Matrix b: ");
      printMat ( b );

      Thread threads[] = new Thread[nThreads];
      System.out.println ( "I am the main thread!" );

      for ( int i = 0; i < numRows; i++ )      //row
        for ( int j = 0; j < numCols; j++ ) {  //column 
          threads[k] = new MatMul ( i, j, a, b, c );
          threads[k].start();
          k++;
        }
      try {
        for ( int i = 0; i < k; i++ )
          threads[i].join();
      } catch ( InterruptedException e ) {}

      System.out.println ("Matrix c = a x b: ");
      printMat ( c );
    }

    public static void printMat ( double a[][] )
    {
      int numRows = a.length;
      int numCols = a[0].length;

      for ( int i = 0; i < numRows; i++ ) {
        for ( int j = 0; j < numCols; j++ ) {
          System.out.printf ( "%6.2f, ", a[i][j] );
        }
        System.out.printf("\n");
      }
    }
}

class MatMul extends Thread
{
  private int row, col;
  private double a[][];
  private double b[][];
  private double c[][];

  public MatMul ( int row0, int col0, double a0[][], double b0[][], double c0[][] )
  {
    row = row0;
    col = col0;
    a = a0;
    b = b0;
    c = c0;
  }

  public void run()
  {
    System.out.println ("I am a MatMul  thread!");
    double sum = 0.0;
    int n = a[0].length;      //number of columns

    for ( int i = 0; i < n; i++ )
      sum += a[row][i] * b[i][col];

    c[row][col] = sum;
  }
}

