Java Thread Join Example
In Java, using Thread.join() causes the current thread to wait until the specified thread dies. Using this method allows us to impose an order such that we can make one thread wait until the other completes doing what it needed to do, such as completing a calculation.
This method sometimes causes some confusion among Java developers at all levels from novice to more senior folks. It is important to note that the calling thread will wait until the thread being called completes or the specified duration has elapsed. For illustration, suppose we have several threads mainThread, calcThread, and jmsThread. Suppose now that mainThread needs to wait on calcThread to get the required calculation, but calcThread needs to wait until jmsThread returns the required message from the queue before it can perform the required calculations.
What needs to happen is that inside of calcThread there must be a jsmThread.join(), and inside of mainThread there must be a calcThread.join() such that mainThread waits for calcThread and calcThread waits for jmsThread.
In the example below, I will demonstrate setting up and starting five threads with and without the join() method to help you better understand the concept.
Also, please be aware that Java contains three overloaded methods for join:
Join Methods
Method | Description |
---|---|
join() | Waits until the thread that it is attached it dies |
join(long millis) | Waits at most millis until the thread that it is attached it dies |
join(long millis, int nanos) | Waits at most millis plus nanos until the thread that it is attached it dies |
ThreadJoinExample (without join)
In the example, you will notice from the output below that the main program actually ends before all the threads have even started up. This is because there is a little bit of overhead that takes place when starting threads and the t.start() return almost instantly from the call. Since I am using the default constructor the threads only sleep for 500ms (or half a second).
package com.avaldes.tutorials; import java.util.ArrayList; public class ThreadJoinExample implements Runnable { int sleepTime = 0; public ThreadJoinExample(int sleepTime) { setSleepTime(sleepTime); } public ThreadJoinExample() { setSleepTime(500); } public long getSleepTime() { return sleepTime; } public void setSleepTime(int sleepTime) { this.sleepTime = sleepTime; } public void run() { try { System.out.format("Thread %s started...\n", Thread.currentThread().getName()); Thread.sleep(sleepTime); System.out.format("Thread %s ended...\n", Thread.currentThread().getName()); } catch (InterruptedException e) { System.out.format("Thread %s interrupted...", Thread.currentThread().getName()); } } public static void main(String[] args) throws InterruptedException { System.out.println("Starting ThreadJoinExample without wait..."); for (int i = 1; i< 5; i++) { Thread t = new Thread(new ThreadJoinExample(), "Thread_" + i); t.start(); } System.out.println("Ending ThreadJoinExample..."); } }
Output
Starting ThreadJoinExample without wait... Thread Thread_1 started... Thread Thread_4 started... Ending ThreadJoinExample... Thread Thread_3 started... Thread Thread_2 started... Thread Thread_4 ended... Thread Thread_3 ended... Thread Thread_1 ended... Thread Thread_2 ended...
ThreadJoinExample (with join)
In this second example, I have added an ArrayList so I can add all five threads to it as they get created. I will use this list later in the main program with the join() method. Now you will see that the “main” thread actually will wait until all five threads have completed before completing….
package com.avaldes.tutorials; import java.util.ArrayList; public class ThreadJoinExample implements Runnable { int sleepTime = 0; public ThreadJoinExample(int sleepTime) { setSleepTime(sleepTime); } public ThreadJoinExample() { setSleepTime(500); } public long getSleepTime() { return sleepTime; } public void setSleepTime(int sleepTime) { this.sleepTime = sleepTime; } public void run() { try { System.out.format("Thread %s started...\n", Thread.currentThread().getName()); Thread.sleep(sleepTime); System.out.format("Thread %s ended...\n", Thread.currentThread().getName()); } catch (InterruptedException e) { System.out.format("Thread %s interrupted...", Thread.currentThread().getName()); } } public static void main(String[] args) throws InterruptedException { ArrayList<Thread> threadList = new ArrayList<Thread>(); System.out.println("Starting ThreadJoinExample with wait..."); for (int i = 1; i< 5; i++) { Thread t = new Thread(new ThreadJoinExample(), "Thread_" + i); threadList.add(t); t.start(); } for (Thread t: threadList) { t.join(); } System.out.println("Ending ThreadJoinExample..."); } }
Output
Starting ThreadJoinExample with wait... Thread Thread_1 started... Thread Thread_4 started... Thread Thread_3 started... Thread Thread_2 started... Thread Thread_3 ended... Thread Thread_2 ended... Thread Thread_4 ended... Thread Thread_1 ended... Ending ThreadJoinExample...
Related Posts
- Java Thread, Concurrency and Multithreading Tutorial
This Java Thread tutorial will give you a basic overview on Java Threads and introduce the entire tutorial series on concurrency and multithreading. From here, you will learn about many java thread concepts like: Thread States, Thread Priority, Thread Join, and ThreadGroups. In addition, you will learn about using the volatile keyword and examples on using wait, notify and notifyAll. - Java Thread States - Life Cycle of Java Threads
Get a basic understanding of the various thread states. Using the state transition diagram we show the various states for a Java thread and the events that cause the thread to jump from one state to another. - Creating Java Threads Example
In this post we cover creating Java Threads using the two mechanisms provided in Java, that is, by extending the Thread class and by implementing Runnable interface for concurrent programming. - Java Thread Priority Example
In this post we cover Thread priorities in Java. By default, a java thread inherits the priority (implicit) of its parent thread. Using the setPriority() method you can increase or decrease the thread priority of any java thread. - Java ThreadGroup Example
Sometimes we will need to organize and group our threads into logical groupings to aid in thread management. By placing threads in a threadGroup all threads in that group can be assigned properties as a set, instead of going through the tedious task of assigning properties individually. - Java Thread Sleep Example
We seem to use this method very often to temporarily suspend the current threads execution for a specific period of time. Let's spend some time and familiarize ourselves with what this method actually does. - Java Thread Join Example
In Java, using Thread.join() causes the current thread to wait until the specified thread dies. Using this method allows us to impose an order such that we can make one thread wait until the other completes doing what it needed to do, such as completing a calculation. - Examining Volatile Keyword with Java Threads
When we declare a field as volatile, the JVM will guarantee visibility, atomicity and ordering of the variable. Without it the data may be cached locally in CPU cache and as a result changes to the variable by another thread may not be seen by all other threads resulting in inconsistent behaviour. - Java Threads Wait, Notify and NotifyAll Example
The purpose of using notify() and notifyAll() is to enable threads to communicate with one another via some object on which to performing the locking. A thread using the wait() method must own a lock on the object. Once wait() is called, the thread releases the lock, and waits for another thread to either call notify() or notifyAll() method. - Java Thread Deadlock Example and Thread Dump Analysis using VisualVM
Deadlock is a condition where several threads are blocking forever, waiting for the other to finish but they never do. This tutorial will discuss situations that will lead to Java Thread deadlock conditions and how they can be avoided. In addition, we will discuss using Java VisualVM to pinpoint and analyze the source of the deadlock conditions. - Java Thread Starvation and Livelock with Examples
Starvation occurs when a thread is continually denied access to resources and as a result it is unable to make progress. Thread liveLock is a condition that closely resembles deadlock in that several processes are blocking each other. But with livelock, a thread is unable to make any progress because every time it tries the operation always fails. - Java Synchronization and Thread Safety Tutorial with Examples
One of Java's many strengths come from the fact that it supports multithreading by default as has so from the very onset. One of the mechanisms that Java uses for this is via synchronization. When we use the synchronized keyword in Java we are trying limit the number of threads that can simultaneously access and modify a shared resource. The mechanism that is used in Java's synchronization is called a monitor. - Creating a Thread Safe Singleton Class with Examples
In this tutorial we cover many examples of creating thread-safe singleton classes and discuss some of the shortfalls of each and provide some recommendations on best approaches for a fast, efficient and highly concurrent solution. - Java Threads and Concurrent Locks with Examples
In this tutorial we will focus primarily on using the concurrent utilities and how these can make concurrent programming easier for us.
Leave a Reply