SSPR_25/valiulov_ilyas_lab_1/ThreadPool.java

41 lines
1.3 KiB
Java
Raw Normal View History

2025-02-27 19:12:43 +04:00
import java.util.concurrent.*;
public class ThreadPool {
public static int findMax(int[][] matrix, int numThreads) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
int rows = matrix.length;
int cols = matrix[0].length;
int chunkSize = rows / numThreads;
Future<Integer>[] futures = new Future[numThreads];
for (int i = 0; i < numThreads; i++) {
int startRow = i * chunkSize;
int endRow = (i == numThreads - 1) ? rows : startRow + chunkSize;
futures[i] = executor.submit(() -> findMaxInRange(matrix, startRow, endRow));
}
int max = Integer.MIN_VALUE;
for (Future<Integer> future : futures) {
int localMax = future.get();
if (localMax > max) {
max = localMax;
}
}
executor.shutdown();
return max;
}
private static int findMaxInRange(int[][] matrix, int startRow, int endRow) {
int max = Integer.MIN_VALUE;
for (int i = startRow; i < endRow; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
}
return max;
}
}