49 lines
1.4 KiB
Java
49 lines
1.4 KiB
Java
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
public class ThreadPoolMatrixDivider {
|
|
public static void divideMatrix(int[][] matrix, int numThreads) {
|
|
long startTime = System.currentTimeMillis();
|
|
|
|
int max = findMax(matrix);
|
|
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
|
|
|
|
for (int i = 0; i < matrix.length; i++) {
|
|
final int row = i;
|
|
executor.submit(() -> {
|
|
for (int j = 0; j < matrix[row].length; j++) {
|
|
matrix[row][j] /= max;
|
|
}
|
|
});
|
|
}
|
|
|
|
executor.shutdown();
|
|
try {
|
|
executor.awaitTermination(1, TimeUnit.MINUTES);
|
|
} catch (InterruptedException e) {
|
|
e.printStackTrace();
|
|
}
|
|
|
|
long endTime = System.currentTimeMillis();
|
|
System.out.println("ThreadPoolExecutor: " + (endTime - startTime) + "ms");
|
|
}
|
|
|
|
private static int findMax(int[][] matrix) {
|
|
int max = matrix[0][0];
|
|
for (int[] row : matrix) {
|
|
for (int value : row) {
|
|
if (value > max) {
|
|
max = value;
|
|
}
|
|
}
|
|
}
|
|
return max;
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
int[][] matrix = MatrixGenerator.generateMatrix(1000, 1000);
|
|
divideMatrix(matrix, 4);
|
|
}
|
|
}
|