This is my ProcessDataFileParallel.Java file. I'm taking numbers from a .txt file and putting it into an array in Java. While it works, I would like to improve the code and possibly change some algorithms to better alternatives.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ProcessDataFileParallel {
public static void main(String[] args) throws IOException {
int[] array = new int[100000];
int index = 0;
Scanner inputFile = null;
Scanner scan = new Scanner(System.in);
boolean running = false;
String emptyString;
FileReader file = new FileReader("dataset529.txt");
BufferedReader br = new BufferedReader(file);
emptyString = br.readLine();
try {
while ((emptyString = br.readLine()) != null) {
array[index++] = Integer.parseInt(emptyString);
}
} finally {
if (br.readLine() == null)
br.close();
}
inputFile = new Scanner(file);
// Read File from Dataset529.txt
if(inputFile != null){
System.out.println("Number of integers in: " + file);
try{
while (inputFile.hasNext() && inputFile.hasNextInt()){
array[index] = inputFile.nextInt();
index++;
inputFile.next();
}
}finally{
inputFile.close();
}
// Print dataset529.txt to Array in Java with For Loop below.
for (int ai = 0; ai < index; ai++){
System.out.println("Array Index: " + "(" + ai + ")" + "== >" + " " + array[ai]);
}
System.out.println("How many Threads?"); // Scanner - Ask user how many threads
int n = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
Thread[] myThreads = new Thread[n]; // Variable n placed here to determine how many Threads user wanted
Worker[] workers = new Worker[n]; // Variable N placed here - the number user specified will determine # of workers.
int range = array.length/n; //divides the array into n threads (what scanner specifies)
for (index = 0; index < n; index ++){
int start = index*range;
int end = start + range;
workers[index] = new Worker(start,end, array);
}
for( index = 0; index < n; index++){
myThreads[index] = new Thread(workers[index]);
myThreads[index].start();
}
if (running){
for (Thread t : myThreads) {
if (t.isAlive()) {
running = true;
break;
}
}
} while (running);
for (Worker worker : workers) {
System.out.println("Max = " + worker.getMax());
}
}
}
}
Worker
class:
public class Worker implements Runnable {
private int start;
private int end;
private int randomNumbers[];
int max = Integer.MIN_VALUE;
public Worker(int start, int end, int[] randomNumbers) {
this.start = start;
this.end = end;
this.randomNumbers = randomNumbers;
}
public void run() {
for (int index = start; index < end; index++) {
if (randomNumbers[index] >max)
max = randomNumbers[index];
}
}
public int getMax() {
return max;
}
}
Is there any way I can improve/condense my code? Also, is there any way to possibly do alternatives that would be better?