- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想找到二维数组的最大值。我在没有使用多线程的情况下找到了这个值。如何使用多线程找到二维数组的最大值?我想比较不同方式求数组最大值的速度。
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 tofindMax(matrix[i])
(hint: useExecutorService
) in the thread, once max is found, fill it in toi
th position of a one dimensional array calledresults
in the thread, indicate its completion(hint: useCountDownLatch
)In the main thread, wait till all threads finish ( hint: use
CountDownLatch
) Now callfindMax(results)
and you have the maxiumum from matrix.
注意事项:我们是否需要 fork 与矩阵中的行一样多的线程?那么我们是否使用具有行数的 FixedThreadPool
?
关于java - 如何使用多线程在java中找到二维数组的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643078/
我是一名优秀的程序员,十分优秀!