0

Java – Block main thread until another Thread completes

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

Javadoc

Join method with time to wait in milliseconds

Javadoc

Join method with milliseconds + nanoseconds

Javadoc

We will use only the first two methods mentioned above.

Join method Example

Output

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

Output

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

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert