简体   繁体   中英

Join()ing on multiple threads and handling leaked output

I'm solving a multi-threaded problem in Java and have the core problem itself resolved, but my output isn't what I'd expect.

I have a main thread that spins new threads that each perform their tasks. It looks like the following (pseudocode):

initializeThreads();            // Creates the new threads
startThreads();                 // Starts the new threads
sleep( duration );              // Lets the threads run for `duration` time
shutdownThreads();              // interrupt the threads
printOutput();                  // output the results to the console

// definition of shutdownThreads() is at the end of my question

My issue happens upon trying to join() on each thread in my list of threads. Every now and then my program gets caught in an endless loop because I'm guessing the interrupt() I call on my list of threads doesn't happen fast enough compared to the join() and not all the threads get interrupted.

My other issue occurs when the program does shutdown the threads correctly and print the termination output. While the program is running each thread has messages that it logs to the console, and after I interrupt the threads and display the final program message some of these thread-specific logging messages leak out to the console.

For example, let's say one of my threads outputs "Thread-1 waiting for lock on object..." while it runs, and the main program finally wakes itself up, terminates the thread, and outputs "Program finished" . Sometimes, the thread-specific message will show up after the program termination message.

If anyone could help me figure out how to stop this from happening please let me know!

shutdownThreads()

   private void shutdownThreads() {

    Thread t;
    for (int i = 0; i < threads.size(); i++) {
      t = threads.get(i);

      t.interrupt();
     }

    for (int i = 0; i < threads.size(); i++) {
      t = threads.get(i);
      try {
        t.join();
      } catch (InterruptedException e) {
       System.out.println("Interrupted while waiting on thread to exit");
      }
    }

}

EDIT: One thing I thought of doing is rewriting shutdownThreads() to do this:

for (int i = 0; i < threads.size(); i++) {
  Thread t = threads.get(i);

  t.interrupt();

  while (!t.isInterrupted()) ;
}

but this doesn't seem too elegant.

您编辑过的代码位于底部,在两次迭代for()之前,这将是一个永远的循环。

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