multithread matrix
public class MatrixMultiplicationMultithreaded {
public static void main(String[] args) {
int N = 500; // Matrix size (N x N)
// Initializing matrices A and B
int[][] A = new int[N][N];
int[][] B = new int[N][N];
int[][] C = new int[N][N]; // Result matrix
// Randomly initializing matrices A and B
initializeMatrix(A);
initializeMatrix(B);
// Multithreaded matrix multiplication
long startTime = System.nanoTime();
multiplyMatricesMultithreaded(A, B, C, N);
long endTime = System.nanoTime();
long duration = (endTime - startTime); // Time in nanoseconds
System.out.println("Multithreaded Matrix Multiplication took: " + duration + " nanoseconds.");
}
// Initialize matrix with random values
public static void initializeMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = (int)(Math.random() * 10); // Random values between 0 and 9
}
}
}
// Multithreaded Matrix Multiplication
public static void multiplyMatricesMultithreaded(int[][] A, int[][] B, int[][] C, int N) {
Thread[] threads = new Thread[N];
// Each thread handles one row of the result matrix
for (int i = 0; i < N; i++) {
final int row = i;
threads[i] = new Thread(() -> {
for (int j = 0; j < N; j++) {
C[row][j] = 0;
for (int k = 0; k < N; k++) {
C[row][j] += A[row][k] * B[k][j];
}
}
});
threads[i].start(); // Start the thread
}
// Wait for all threads to complete
try {
for (int i = 0; i < N; i++) {
threads[i].join(); // Wait for thread to finish
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Comments
Post a Comment