Write a program in Java to perform the following operations on Matrix
using multithreading. Get the required input matrix from the user and after
that run three threads to perform the following operation.
a. Addition
b. Subtraction
c. Multiplication
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter number of rows: ");
int rows=input.nextInt();
System.out.println("Enter number of columns: ");
int cols=input.nextInt();
int [][] matrix1=new int [rows][cols];
int [][] matrix2=new int [rows][cols];
System.out.println("Enter first matrix: ");
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
matrix1[i][j]=input.nextInt();
}
}
System.out.println("Enter second matrix: ");
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
matrix2[i][j]=input.nextInt();
}
}
//addition
Matrix thread1=new Matrix();
thread1.addition(matrix1,matrix2,rows,cols);
//subtraction
Matrix thread2=new Matrix();
thread2.subtraction(matrix1,matrix2,rows,cols);
//multiplication
Matrix thread3=new Matrix();
thread3.multiplication(matrix1,matrix2,rows,cols);
}
}
class Matrix extends Thread{
public void addition(int [][] A, int [][] B, int r, int c){
int [][] sum=new int[r][c];
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
sum[i][j]=A[i][j]+B[i][j];
}
}
System.out.println("The first matrix + second matrix is: ");
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
System.out.print(sum[i][j]+" ");
}
System.out.println();
}
}
public void subtraction(int [][] A, int [][] B, int r, int c){
int [][] sub=new int[r][c];
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
sub[i][j]=A[i][j]-B[i][j];
}
}
System.out.println("The first matrix - second matrix is: ");
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
System.out.print(sub[i][j]+" ");
}
System.out.println();
}
}
public void multiplication(int [][] A, int [][] B, int r, int c){
int [][] mul=new int[r][c];
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
mul[i][j]=0;
for(int k=0;k<r;k++)
{
mul[i][j]+=A[i][k]*B[k][j];
}
}
}
System.out.println("The first matrix * second matrix is: ");
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
System.out.print(mul[i][j]+" ");
}
System.out.println();
}
}
Comments
Leave a comment