isAlive() and join() methods of Thread Class in Java
Thread class in java provides numerous methods that are very essential in order to understand the working of threads as the thread stages are triggered by them. Java multi-threading provides two ways to find with the help of these two methods is isAlive() and join() method one thread get to know when another thread has ended. Let us do depict stages of the lifecycle of the thread via the below image which helps us to connect dots to understand these methods’ workings.
Method 1: isAlive()
It tests if this thread is alive. A thread is alive if it has been started and has not yet died. There is a transitional period from when a thread is running to when a thread is not running. After the run() method returns, there is a short period of time before the thread stops. If we want to know if the start method of the thread has been called or if the thread has been terminated, we must use the isAlive() method. This method is used to find out if a thread has actually been started and has yet not terminated.
final boolean isAlive()
Return Value: Boolean value returns
Note: While returning this function returns true if the thread upon which it is called is still running. It returns false otherwise.
geeks true true geeks forgeeks forgeeks
Method 2: join() Method
When the join() method is called, the current thread will simply wait until the thread it is joining with is no longer alive. Or we can say the method that you will more commonly use to wait for a thread to finish is called join( ). This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to specify the maximum amount of time that you want to wait for the specified thread to terminate.
final void join() throws InterruptedException
Here is an improved version of the preceding example that uses join( ) to ensure that the main thread is the last to stop. It also demonstrates the isAlive( ) method.
Example 1: Without join() method
geeks geeks forgeeks forgeeks
Example 2: With join() method
geeks forgeeks geeks forgeeks
This article is contributed by Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.