I am trying to implement the use of a queue into my code. The point is that I want it to print out the total amount of Words in the files, which means I somehow need it to add all the results together when they're done.
Currently, what my program does, is that I have a reader that runs through files, and returns a string containg the name of the file, and the amount of words in it. Then I use my main method to run through a for-loop for each argument given in the args array. Everytime we go through a new document to check how many words there is, we make it a new thread.
public static void main(final String[] args) {
Thread t = null;
if (args.length >= 1) {
String destinationFileName = args[(args.length-1)];
for (int l = 0; l < (args.length); l++) {
final int q = l;
final Thread y = t;
Runnable r = new Runnable() {
public void run() {
String res = readTextFile(args[q]);
System.out.println(res);
}
};
t = new Thread(r);
t.start();
}
} else {
System.err.println("Not enough input files");
}
}
So, how do I make a queue that somehow makes them wait for each other so that it doesn't make the mistake of adding to the result on the exact same time?
A blocking queue seems unnecessary here. Just have each thread add its results to a thread-safe list, which can be constructed like this:
Next you want to wait until all threads are done before aggregating the results. You can do this by calling
join
on each thread. Add each of your threads to a list calledthreads
, then once all the threads have been started, call this:This code will effectively wait for every thread to finish before moving on.