public class MaxThreadApp {
public static void main(String[] args) {
Array_2D a2 = new Array_2D(1000, 1000);
double[][] array2D = a2.generator();
double max = 0.0;
long start = 0, end = 0;
Thread[] maxThread = new MaxThread[array2D.length];
for (int i = 0; i < maxThread.length; i++) {
maxThread[i] = new MaxThread(array2D[i]);
maxThread[i].start();
}
try {
start = System.currentTimeMillis();
for (int i = 0; i < maxThread.length; i++) {
maxThread[i].join();
max = Math.max(max, ((MaxThread) maxThread[i]).getMax());
}
end = System.currentTimeMillis();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The max number is: " + max);
System.out.println("Multi Threads used time: " + (end - start) + "ms");
max = 0.0;
start = System.currentTimeMillis();
for (int i = 0; i < array2D.length; i++) {
for (int j = 0; j < array2D[i].length; j++) {
max = Math.max(max, array2D[i][j]);
}
}
end = System.currentTimeMillis();
System.out.println("The max number is: " + max);
System.out.println("Single Thread used time: " + (end - start) + "ms");
}
}
public class MaxThread extends Thread {
private double[] array;
private double max = 0.0;
public MaxThread(double[] array) {
this.array = array;
}
public void run() {
for (int i = 0; i < array.length; i++) {
max = Math.max(max, array[i]);
}
}
public double getMax() {
return max;
}
}
public class Array_2D {
private int row;
private int column;
public Array_2D(int row, int column) {
this.row = row;
this.column = column;
}
public double[][] generator() {
double[][] _2D_array = new double[row][column];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
_2D_array[i][j] = Math.random() * 101;
}
}
return _2D_array;
}
}
The max number is: 100.9999778276479
Multi Threads used time: 1ms
The max number is: 100.9999778276479
Single Thread used time: 16ms