-1

I am working on a homework assignment due next week. We are supposed to have three threads. The first one reads text from a text file, the next one reverses every other word and does not include punctuation in the reversal, and the last thread takes the reversed words from the queues and writes them back to a new text file.

The BlockingQueues can only be of length 2. I have successfully read from the file and reversed the words. However I am having trouble writing to a text file. So far it is only writing the first word. Here is the code in the final output thread's run method. I am not sure how to have the thread write the two words currently in the queue and then stop and wait for the queue to fill up with new reversed words from the other thread

  public void run() {
    while(true){
       try {
           FileWriter writer = new FileWriter(file);
           try {

               writer.write(out.take() + " ");
           } catch (InterruptedException ex) {
               Logger.getLogger(outputClass.class.getName()).log(Level.SEVERE, null, ex);
           }
           writer.close();
       } catch (IOException ex) {
           Logger.getLogger(outputClass.class.getName()).log(Level.SEVERE, null, ex);
       }   
}

}

1 Answers1

0

Before trying to write data, you need to check if data is present in the queue. If not, you can use Thread.sleep() to yield to the other threads then try again when the thread wakes up, or you can create a wait condition, and have the other threads notify the wait when they have written data.

CharlieS
  • 1,432
  • 1
  • 9
  • 10
  • I know I have the words in the queue because I used a println method to show them. The rule of the assignment was that the threads cannot have references to each other. If I try to say while(!out.isEmtpy) and then write to the file, my program never makes it past the first two words. It fills up the queue and never removes from it. Thank you for your help. I am very confused when it comes to Threads. Should I have a join statement in the main method? How do I continuously write to the same file and keep adding the new words in the queue? – user3370950 Oct 24 '14 at 02:28
  • You know it, but your program doesn't! Your code needs to account for when there is and when there isn't. You have now asked a different question. You need to understand threads, sleeps, waits and synchronisation better. There are many ways to solve the threading issue. Start a different question regarding dynamic file IO. – CharlieS Oct 24 '14 at 02:46