I have an issue with a Reader/Writer implementation. I'm supposed to write a Reader class that takes a String from the console and adds it to a Queue and a Writer class that removes the String from the same queue and outputs it onto the console, using Threads. I wrote my program for just one String (type one String and it outputs that String through the Queue) and that worked perfectly. Now I'm struggling to make it so that I can input multiple Strings, press Enter and the Reader then adds it to the Queue and the Writer then displays it. If the String quit
is typed, both threads have to stop and the program should end.
My Reader idea looks like this:
Scanner k = new Scanner(System.in);
in = k.nextLine();
if(in.equals("quit"))
System.exit(0);
synchronized(q){
while(!(in.equals("quit"))){
// System.out.println(q.isEmpty());
q.enqueue(in);
in = k.next();
if(in.equals("quit"))
System.exit(0);
}
}
And my Writer looks like this:
public void run(){
synchronized(q){
while(!q.isEmpty()){
String out = q.dequeue();
System.out.println(out);
}
}
}
My Reader seems to work fine, as I built in Sys.out.(q.isEmpty)
after adding to the queue. It shows me that the queue is filling up, but nothing is output onto the console from the Writer class. Writing quit
stops the program with no issues.
I don't think I understand threads perfectly. My main method just creates the Threads with Thread t1 = new Thread(new Reader(queue));
and the same for Writer
and then starts both threads.