I have a program that sorts though a text file and pulls out the maximum value using 10 threads. How can I then sort through the 10 threads and find the highest value of those 10? My logic would be to store each result in an array and compare that result to the previous, but I'm unsure on how to properly implement it with threading. I added this for loop but it's not correct.Any help would be greatly appreciated!
for (int x = 0; max <=max; x++) {
max = worker.getMax();
System.out.println("Final Max " = max);
}
This is the actual program including the code above. It runs fine without this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class datafile{
public static void main(String[] args) throws IOException {
int[] array = new int[100000];
int count;
int index = 0;
String datafile = "dataset529.txt"; //string which contains datafile
String line; //current line of text file
try (BufferedReader br = new BufferedReader(new FileReader(datafile))) { //reads in the datafile
while ((line = br.readLine()) != null) { //reads through each line
array[index++] = Integer.parseInt(line); //pulls out the number of each line and puts it in numbers[]
}
}
Thread[] threads = new Thread[10];
worker[] workers = new worker[10];
int range = array.length / 10;
for (count = 0; count < 10; count++) {
int startAt = count * range;
int endAt = startAt + range;
workers[count] = new worker(startAt, endAt, array);
}
for (count = 0; count < 10; count++) {
threads[count] = new Thread(workers[count]);
threads[count].start();
}
boolean isProcessing = false;
do {
isProcessing = false;
for (Thread t : threads) {
if (t.isAlive()) {
isProcessing = true;
break;
}
}
} while (isProcessing);
for (worker worker : workers) {
System.out.println("Max = " + worker.getMax());
}
for (int x = 0; max <=max; x++) {
max = worker.getMax();
System.out.println("Final Max " = max);
}
}
public static class worker implements Runnable {
private int startAt;
private int endAt;
private int randomNumbers[];
int max = Integer.MIN_VALUE;
public worker(int startAt, int endAt, int[] randomNumbers) {
this.startAt = startAt;
this.endAt = endAt;
this.randomNumbers = randomNumbers;
}
@Override
public void run() {
for (int index = startAt; index < endAt; index++) {
if (randomNumbers != null && randomNumbers[index] > max)
max = randomNumbers[index];
}
}
public int getMax() {
return max;
}
}
}