Write a Java program that uses multithreading to implement a 3x3 matrix multipli
ID: 3545439 • Letter: W
Question
Write a Java program that uses multithreading to implement a 3x3 matrix multiplication. The specifications for the program are given as follows:
Assume that the content of input matrices A and B are entered by user from standard input (keyboard). Your program needs to calculate: Result = A x B, where A and B are the input matrices, x is the matrix multiplication operation, and Result is the resulting matrix. Implement multithreading in such a way that each thread calculates one element (i.e., multiply the elements of the ith row from matrix A and the jth column from matrix B, and adds the results to get the value to be stored at Result[i, j]).
Thanks
Explanation / Answer
import java.lang.*;
import java.io.*;
class MatMulti extends Thread
{
static int A[][];
static int B[][];
static int Result[][];
static int a=2;
int row;
MatMulti(int i)
{
row=i;
this.start();
}
public void run()
{
int i,j;
for(i=0;i<a;i++)
{
Result[row][i]=0;
for(j=0;j<a;j++)
Result[row][i]=Result[row][i]+A[row][j]*B[j][i];
}
}
public static void main(String args[])
{
int i,j,a=3;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the order of Matrix : ");
try
{
a=Integer.parseInt(br.readLine());
}catch(Exception e){}
A=new int[a][a];
B=new int[a][a];
Result=new int[a][a];
System.out.println("Enter the First Matrix : ");
for(i=0;i<a;i++)
{
for(j=0;j<a;j++)
{
try
{
A[i][j]=Integer.parseInt(br.readLine());
}catch(Exception e){}
}
}
System.out.println("Enter the Second Matrix : ");
for(i=0;i<a;i++)
{
for(j=0;j<a;j++)
{
try
{
B[i][j]=Integer.parseInt(br.readLine());
}catch(Exception e){}
}
}
MatMulti mat[]=new MatMulti[a];
for(i=0;i<a;i++)
mat[i]=new MatMulti(i);
try
{
for(i=0;i<a;i++)
mat[i].join();
}catch(Exception e){}
System.out.println("OUTPUT :");
for(i=0;i<a;i++)
for(j=0;j<a;j++)
System.out.println(Result[i][j]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.