# Implement a multi-threaded matrix multiplication program.

• 11-17-2010, 10:00 AM
redasu
Implement a multi-threaded matrix multiplication program.
I am suppose to create a program that will take two parameters: the number of threads
n and and a matrix side length m. It will generate two random-value
square matrices A and B of size m×m each, and feed equal-size
product matrix C = A B. Also, we are assuming that n and m are powers of four, and
also n<m.

Here is my code:

package hwos2;

import java.io.*;
import java.util.*;

public class Main {

private static int i = 1,j = 1;
private static int array1[][] = new int[j][j];
private static int array2[][] = new int[j][j];
private static int array3[][] = new int[j][j];

private static class MultiplyMatrix implements Runnable {
int min, max, tnum = 0;

public MultiplyMatrix(int lower, int higher, int id) {
min = lower;
max = higher;
tnum = id;
}

public void run() {
for (int x = min; x < max; x++) {
for (int y = 0; y < j; y++) {
array3[x][y] = 0;
for (int count = 0; count <j; count++) {
array3[x][y] += array1[x][count] * array2[count][y];
}
}
}
}
}

public static void main(String args[]) throws InterruptedException
{

try
{
long start = System.currentTimeMillis();
Random randomGenerator = new Random();

System.out.print("Enter the order of Matrix m : ");

System.out.print("Enter the number of threads : ");

int array1[][] = new int[j][j];
int array2[][] = new int[j][j];
System.out.println("array1 is:");
for(int m=0;m<j;m++)
{
for(int n=0;n<j;n++)
{
array1[m][n]= randomGenerator.nextInt(10);
System.out.print(array1[m][n]+"\t");
}
System.out.print("\n");
}
System.out.println("array2 is:");
for(int m=0;m<j;m++)
{
for(int n=0;n<j;n++)
{
array2[m][n]= randomGenerator.nextInt(10);
System.out.print(array2[m][n]+"\t");
}
System.out.print("\n");
}

for (int c = 0; c < i-1; c++) {

threads[c] = new Thread( new MultiplyMatrix(j/i * c, j/i * (c + 1) , c) );
}
for (int c = 0; c < i; c++) {
}
System.out.println("The result is:");
for (int x = 0; x < 1000; x++) {
for (int y = 0; y < 1000; y++) {

System.out.println(array3[x][y]);
}
}
long end= System.currentTimeMillis() ;
long runTime= end - start;
System.out.println("Total time: " +runTime + " ms");

}

catch (Exception e) {
e.printStackTrace();
}
}

}

// code ends here

for some reason I receive the following error: