How does one thread know that another thread has ended? The Thread class provides a way to answer this question.
There are two ways to determine whether a thread ends. First, isAlive() can be called in the thread. This method is defined by Thread, and its usual form is as follows:
final boolean isAlive( )
If the called thread is still running, the isAlive() method returns true, and if not, false. However, isAlive() is rarely used. The more commonly used method to wait for the thread to end is to call join(), which is described as follows:
final void join( ) throws InterruptedException
This method waits for the called thread to end. This name comes from the concept that requires a thread to wait until the specified thread participates. The additional form of join() allows a maximum time to be defined for waiting for the specified thread to end. Below is an improved version of the previous example. Use join() to ensure that the main thread ends. Similarly, it also demonstrates the isAlive() method.
// Using join() to wait for threads to finish. class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); ("New thread: " + t); (); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { (name + ": " + i); (1000); } } catch (InterruptedException e) { (name + " interrupted."); } (name + " exiting."); } } class DemoJoin { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); NewThread ob3 = new NewThread("Three"); ("Thread One is alive: "+ ()); ("Thread Two is alive: "+ ()); ("Thread Three is alive: "+ ()); // wait for threads to finish try { ("Waiting for threads to finish."); (); (); (); } catch (InterruptedException e) { ("Main thread Interrupted"); } ("Thread One is alive: "+ ()); ("Thread Two is alive: "+ ()); ("Thread Three is alive: "+ ()); ("Main thread exiting."); } }
The program output is as follows:
New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] Thread One is alive: true Thread Two is alive: true Thread Three is alive: true Waiting for threads to finish. One: 5 Two: 5 Three: 5 One: 4 Two: 4 Three: 4 One: 3 Two: 3 Three: 3 One: 2 Two: 2 Three: 2 One: 1 Two: 1 Three: 1 Two exiting. Three exiting. One exiting. Thread One is alive: false Thread Two is alive: false Thread Three is alive: false Main thread exiting.
As you can see, after calling join(), the thread terminates execution.