gpt4 book ai didi

java - 如何使用多线程在java中找到二维数组的最大值

转载 作者:行者123 更新时间:2023-11-30 08:01:27 24 4
gpt4 key购买 nike

我想找到二维数组的最大值。我在没有使用多线程的情况下找到了这个值。如何使用多线程找到二维数组的最大值?我想比较不同方式求数组最大值的速度。

public class Search {

public int[][] fillMatrix(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() * 1000);
}
}
return matrix;
}

public int searchMaxValue(int[][] matrix, int row, int column) {
int max = matrix[0][0];
for (int a = 0; a < row; a++) {
for (int b = 0; b < column; b++) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (matrix[a][b] > max) {
max = matrix[a][b];
}
}
}
return max;
}


public static void main(String[] args) {

Search search = new Search();
int[][] matrix = new int[4][100];
search.fillMatrix(matrix);
long start = System.currentTimeMillis();
int max = search.searchMaxValue(matrix, 4, 100);
long end = System.currentTimeMillis();
System.out.println("Max value is " + max);
System.out.println("Time for execution: " + (end - start));
}
}

最佳答案

下面是您将如何实现它的概述。我没有刻意提供代码,您可以享受自己实现它的乐趣。

create a method to findmax out of an array lets call it findMax(int[]
input)

for each sub array in 2D array (can be accessed using matrix[i])
start a thread to findMax(matrix[i]) (hint: use ExecutorService) in the thread, once max is found, fill it in to ith position of a one dimensional array called results in the thread, indicate its completion(hint: use CountDownLatch)

In the main thread, wait till all threads finish ( hint: use CountDownLatch) Now call findMax(results) and you have the maxiumum from matrix.

注意事项:我们是否需要 fork 与矩阵中的行一样多的线程?那么我们是否使用具有行数的 FixedThreadPool

关于java - 如何使用多线程在java中找到二维数组的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com