DAS_2024_1/emelyanov_artem_lab_5/MatrixMultiplication.java

45 lines
1.5 KiB
Java
Raw Normal View History

2024-10-18 17:41:49 +04:00
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MatrixMultiplication {
public static int[][] multiply(int[][] matrixA, int[][] matrixB, int numThreads) {
int n = matrixA.length;
int[][] result = new int[n][n];
if (numThreads == 1) {
// Последовательное умножение
for (int i = 0; i < n; i++) {
multiplyRow(matrixA, matrixB, result, i);
}
} else {
// Многопоточное умножение
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < n; i++) {
final int row = i;
executor.submit(() -> multiplyRow(matrixA, matrixB, result, row));
}
executor.shutdown();
try {
// Ожидаем завершения всех задач
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return result;
}
private static void multiplyRow(int[][] matrixA, int[][] matrixB, int[][] result, int row) {
int n = matrixA.length;
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
result[row][j] += matrixA[row][k] * matrixB[k][j];
}
}
}
}