I got a project where I have to make a WordCounter.. I have made that and it works fine.
Then I need to make a queue so I can get the different lenght of the text and add them together and print out that.
I have made a queue, and tried to get into print it out where it also print out how the nummbers of word in the text, and can see that it add the numbers to the queue..
But then I cant figure out how I get those numbers out of the queue so I can add them together
Here is my WordCounterTester
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class WordCountTest {
public static void main(String[] args){
final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
for(int i = 0; i< args.length; i++){
Runnable r = new WordCount(args[i],queue);
Thread t = new Thread(r);
t.start();
}
}
}
And my WordCounter
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
class WordCount implements Runnable {
public int result;
private String s;
Thread runner;
private BlockingQueue<String> queue;
public WordCount(String s, BlockingQueue<String> queue){
this.s = s;
this.queue = queue;
}
public void run() {
try{
FileReader fr = new FileReader(s);
Scanner scanner = new Scanner(fr);
for(int i = 0; true; i++){
result = i;
scanner.next();
}
}catch(FileNotFoundException e){
System.out.println("Du har skrevet en fil der ikke findes, den fil vil blive skrevet ud med 0 ord");
}
catch(NoSuchElementException e){}
System.out.println(s + ": " + result);
Integer.toString(result);
queue.add(result + "");
System.out.println(queue);
}
}
What I get right now when I run the program with 6 different .txt, the order can be different because of it is multi threading so different which one get first done 🙂
5.txt: 1
[1]
6.txt: 90
[1, 90]
4.txt: 576
[1, 90, 576]
3.txt: 7462
[1, 90, 576, 7462]
1.txt: 7085
[1, 90, 576, 7462, 7085]
2.txt: 11489
[1, 90, 576, 7462, 7085, 11489]
Do anyone have a idea to how I can make that work?
I think what you are missing is that
mainneeds to join with the threads that it has spawned after each of them has added their per-file count to the queue.In the code here I’ve implemented @Ben van Gompel’s suggestion of adding an
Integerto the queue not aString.You could also use an
AtomicIntegerclass and do something like:Inside of the WordCount code you would use the
AtomicIntegerlike: