title: Java multi-thread matrix multiplication
body: <p>Trying to get a multi-threaded matrix multiplication to work in Java. It is given a (m x n) matrix, a (n x k) matrix and 't' threads to perform the operation on.</p>
  <p>My program works when the matrices are square and t == n. When running with t &lt; n, the other threads do not pick up the additional operations, and it returns a partially completed matrix. When the matrices are not square, the additional threads return array out of bounds errors and do not run. I would really appreciate any advice. Here are the relevant code snippets</p>
  <p>Beginning threads. multipliers is an array of MatrixMultiplier, a class defined later.</p>
  <pre><code>Multiply multiply = new Multiply(cols_mat, rows_mat2);
  
  for (int i = 0; i &lt; threads; i++) {
      multipliers[i] = new MatrixMultiplier(multiply);
  }
  
  for (int i = 0; i &lt; threads; i++) {
      my_threads[i] = new Thread(multipliers[i]);
  }
  
  for (int i = 0; i &lt; threads; i++) {
      my_threads[i].start();
  }
  
  for (int i = 0; i &lt; threads; i++) {
      my_threads[i].join();
  }
  </code></pre>
  <p>Multiply class which defines the matrix multiplication</p>
  <pre><code>class Multiply extends MatrixMultiplication {
      private int i;
      private int j;
      private int chance;
  
      public Multiply(int i, int j) {
          this.i = i;
          this.j = j;
          chance = 0;
      }
  
      public synchronized void multiplyMatrix() {
          int sum = 0;
          int a = 0;
          for (a = 0; a &lt; i; a++) {
              sum = 0;
              for (int b = 0; b &lt; j; b++) {
                  sum = sum + mat[chance][b] * mat2[b][a];
              }
              result[chance][a] = sum;
          }
  
          if (chance &gt;= i)
              return;
          chance++;
      }
  }
  </code></pre>
  <p>And the matrix multiplier</p>
  <pre><code>class MatrixMultiplier implements Runnable {
      private final Multiply mul;
  
      public MatrixMultiplier(Multiply mul) {
          this.mul = mul;
      }
  
      @Override
      public void run() {
          mul.multiplyMatrix();
      }
  }
  </code></pre>
  <p>Where I personally think the issue lies is with <code>if (chance &gt;= i) return;</code> but I have not found a way to incorporate a thread's column responsibilities with the program still working. Again, any advice pointing me in the right direction would be greatly appreciated.</p>