Matrix Multiplication using threads in java
Matrix Multiplication using threads in java
import java.util.*;
class mat {
static int[][] mat;
static int[][] mat2;
static int[][] result;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int n1 = sc.nextInt();
int m1 = sc.nextInt();
mat = new int[n][m];
mat2 = new int[n1][m1];
result = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat[i][j] = sc.nextInt();
}
}
for (int i = 0; i < n1; i++) {
for (int j = 0; j < m1; j++) {
mat2[i][j] = sc.nextInt();
}
}
try {
Multiply multiply = new Multiply(n, m);
MatrixMultiplier thread1 = new MatrixMultiplier(multiply);
MatrixMultiplier thread2 = new MatrixMultiplier(multiply);
MatrixMultiplier thread3 = new MatrixMultiplier(multiply);
Thread th1 = new Thread(thread1);
Thread th2 = new Thread(thread2);
Thread th3 = new Thread(thread3);
th1.start();
th2.start();
th3.start();
th1.join();
th2.join();
th3.join();
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
class Multiply extends mat {
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;
try{
for (a = 0; a < i; a++) {
sum = 0;
for (int b = 0; b < j; b++) {
sum = sum + mat[chance][b] * mat2[b][a];
}
result[chance][a] = sum;
}}catch(Exception e){}
if (chance >= i)
return;
chance++;
}
}
class MatrixMultiplier implements Runnable {
private final Multiply mul;
public MatrixMultiplier(Multiply mul) {
this.mul = mul;
}
public void run() {
try{
mul.multiplyMatrix();}catch(Exception e){}
}
}
OUTPUT :
2 2
2 2
1 2
3 4
5 6
7 8
19 22
43 50
Comments
Post a Comment