6 Replies Latest reply: Sep 21, 2009 5:01 PM by 796440 RSS

    Waiting for a thread to terminate with Thread.join and Thread.isAlive()

    807580
      Hi,

      I'm wondering if there's a caveat with this code (which is a canonical example of some more complex code). The part that needs attention is in the "Foo.stop()" method.
      class Foo {
         private volatile boolean mustStop_ = false;
         private final Thread thread_ = new Thread(new Runnable() {
            @Override
            public void run() {
               while (!mustStop_) {
                  try {
                     System.out.println("Worker thread: looping");
                     Thread.sleep(300);
                  } catch (InterruptedException e) {
                     System.out.println("Worker thread: interrupted while sleeping");
                  }
               }
            }
         });
         
         void start() {
            thread_.start();
         }
         
         void stop() {
            mustStop_ = true;
            thread_.interrupt();   // Not necessary, but will wait less...
            do {
               try {
                  thread_.join();
               } catch (InterruptedException e) { }
            } while (thread_.isAlive());
         }
      }
      
      public final class Main {
         public static void main(String[] args) {
            Foo f = new Foo();
            
            f.start();
            try {
               Thread.sleep(1000);
            } catch (InterruptedException e) { }
            f.stop();
         }
      }
      Is there's any caveat of waiting for a thread to terminate this way ? I personally don't see any, but I don't know, I might be missing something.

      Thanks