Determining When a Thread Has Finished - Java Thread

Java examples for Thread:Thread Operation

Description

Determining When a Thread Has Finished

Demo Code


public class Main {
  public static void main(String[] argv) throws Exception {
    // Create and start a thread
    Thread thread = null;/*from www  .  j  a  v  a2  s .c  o m*/
    thread.start();

    // Check if the thread has finished in a non-blocking way
    if (thread.isAlive()) {
      // Thread has not finished
    } else {
      // Finished
    }

    // Wait for the thread to finish but don't wait longer than a
    // specified time
    long delayMillis = 5000; // 5 seconds
    try {
      thread.join(delayMillis);

      if (thread.isAlive()) {
        // Timeout occurred; thread has not finished
      } else {
        // Finished
      }
    } catch (InterruptedException e) {
      // Thread was interrupted
    }

    // Wait indefinitely for the thread to finish
    try {
      thread.join();
      // Finished
    } catch (InterruptedException e) {
      // Thread was interrupted
    }
  }
}

Related Tutorials