简体   繁体   中英

Thread finishing execution before printing

I am writing to a file (Java) while I execute some code. Below you can find the code used, which is executed by the "Thread B", invoked by the JVM.

writer = new PrintWriter(new BufferedWriter(new FileWriter("table.csv")));

(...)


while ( (m_bEnExecution) && (!m_bFinTestRules) ) {

   //Calculate new rule
   CalculateNewRule(writer);
}

writer.close();

Inside the CalculateNewRule method, a new instantiation of an AssociationRule is created, which will receive the writer as an instance variable. One of the functions inside AssociationRule does the printing.

writer.println(outputRule);
writer.flush();

The problem seems to be that this function is invoked by an AWT thread, and the last line to be written to the file, inside the CalculateNewRule(writer) method will never be written, unless I explicitly force the execution of the thread to stop, after the while cycle. Any idea on what the problem might be? Is there any elegant way to deal with this problem?

In one answer I was suggested to set the printing thread as a daemon thread, but I don't know how to do that on that specific thread.

It may be the calling thread is getting over before this thread finishes. Use a daemon thread if this is the case. Provide more details maybe we can help.

Is that "(m_bEnExecution) && (!m_bFinTestRules)" always equals true??

I suggest that as below:

try {
  while ( (m_bEnExecution) && (!m_bFinTestRules) ) {

    //Calculate new rule
    CalculateNewRule(writer);
    writer.flush();
  }
}
catch (Exception e) {
  e.printStackTrace();
}
finally {
  writer.close();
}

But you still need to make sure that you will not make the infinite loop.

You are not providing much code but anyway.

What do you mean:

force the execution of the thread to stop

You are using a BufferedWriter so unless you flush , close etc the writer you are not sure it has written everything in the buffer.

If you want to be sure just choose one of these methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM