Ihor Starodubets - 1 year ago 178

Java Question

I want to find the maximum value of the two-dimensional array. I found this value without using multithreading. How do I find the maximum value of the two-dimensional array using multithreading? I want to compare the speed of finding the maximum value of the array in different ways.

`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));

}

}

Answer Source

Here is the outline how you would go about implementing this. I am not providing code intentionally, so that you can have the joy of implementing it yourself.

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`i`

th 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.

Considerations: Do we need to fork as many threads as the rows in matrix? So do we use a `FixedThreadPool`

with number of rows ?