Determining When a Thread Has Finished

This example demonstrates a few ways to determine whether or not a thread has returned from its run() method.
// Create and start a thread Thread thread = new MyThread(); 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 }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.