I have made a program that counts the occurrences of a target string in a file. It is supposed to use parallelism to accomplish this but I cant seem to figure out how to write run() to only evaluate a portion of the file so that a different thread of it can evaluate the rest of the file. At least, this is my understanding of parallelism. I've been in the docs and watching videos for a couple days, and really just need someone to explain it to me; not how to step by step solve my particular problem per se, but to explain multi-threading using something more than a main method with a loop that prints the thread id. I know my class needs to implement Runnable and that run() needs to be overridden. I'm unsure about how I'm supposed to write run() to only process a part of the file when I cant pass it parameters.
public static void main(String[] args) {
new Thread(new Test()).start();
new Thread(new Test()).start();
System.out.println("My program counts: " + Test.getTotal() + " occurences of 'the'.");
}
}
public class Test implements Runnable {
private File alice = new File(getCurrentDir() + "/alice.txt");
private String[] words;
private BufferedReader reader;
private StringBuilder sb;
private int count;
private static int total;
public void run() {
getAlice();
for(int i = 0; i < words.length; i++) {
if(words[i].toLowerCase().equals("the")) {
count++;
}
}
total = count;
}
public void getAlice() {
try{
reader = new BufferedReader(new FileReader(alice));
sb = new StringBuilder();
String line = "";
while((line = reader.readLine()) != null) {
sb.append(line);
}
words = sb.toString().split(" ");
} catch (IOException e) {
e.printStackTrace();
}
}
public String getCurrentDir() {
String currDir = System.getProperty("user.dir");
return currDir;
}
public String[] getWords() {
return words;
}
static int getTotal() {
return total;
}
}```