Software Development

Java – Block main thread until another Thread completes

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources

Given a simple Java application with a Thread object, we want to block the main thread until the Thread object completes its execution. The main thread is where the Thread object is created and its start method invoked.

Thread class


The Thread class has the following overloaded methods:

Join method with no argument


Join method with time to wait in milliseconds


Join method with milliseconds + nanoseconds



We will use only the first two methods mentioned above.

Join method Example



The time varies but it is always more than 1 millisecond!

Now, what if we want to wait for exactly 1 millisecond? See the next example.

Join Method with waiting time Example



Based on the console output, the main thread has completed its run and it took additional ~453 milliseconds for the other thread to complete.

You Might Also Like