title: Multithreaded matrix multiplication in Java
body: <p>I'm writing a Java program that uses threads to multiply two matrices. I have the following code: </p>
  
  <pre><code>public class MatrixMultiplication {
      //Declare matrices
      public static int[][] matrix1 = new int[][]{
              {1,2,3,4},{3,2,1,4}
      };
      public static int[][] matrix2 = new int[][]{
              {2,1,3,4},{4,2,5,3}
      };
      public static int[][] result = new int[4][4];
      //Threads
      public static Thread[][] threads = new Thread[4][4];
  
      public static void main(String[] args){
          //create worker threads with M and N hard-coded
          for(int i = 0; i &lt; threads.length; i++) {
              for (int l = 0; l &lt; threads[i].length; l++) {
                  threads[i][l] = new Thread(new Worker(matrix1, matrix2, result, i, l));
              }
          }
          for(int i = 0; i &lt; threads.length; i++){
              for(int l = 0; l &lt; threads[i].length; i++){
                  try {
                      threads[i][l].start();
                      threads[i][l].join();
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
  
          System.out.println("Contents of result matrix");
          for(int i = 0; i &lt; 4; i++)
              for(int l = 0; l &lt; 4; l++){
                  System.out.println("["+i+","+l+"] = "+result[i][l]);
              }
      }
  
  
  }
  
  class Worker implements Runnable{
      int[][] m1;
      int[][] m2;
      int[][] result;
      int row;
      int col;
  
      public Worker(int[][]m1, int[][] m2, int[][] result, int row, int col){
          this.m1 = m1;
          this.m2 = m2;
          this.result = result;
          this.row = row;
          this.col = col;
      }
  
  
      public void run(){result[row][col] = (m1[row][col] * m2[col][col]) + (m1[row][col+1] * m2[col+1][col]);}
  }
  </code></pre>
  
  <p>The programming is throwing an <code>ArrayIndexOutOfBoundsException</code> on multiple lines, notable lines 21 and in the run method of the Worker thread class. I have tried several variations to no avail and am looking for guidance on this. Thank you very much.</p>