Java, Software Development

Java – Block main thread until another Thread completes

The topic on Java Threads is one of the topics with a high learning curve, especially when you are new to programming. Even Java programmers with experience often trip on implementing anything that has to do with Threads in Java. Therefore, this post is more straightforward for everyone to understand. The Java codes block the main thread until another Thread object completes its execution.

Java Thread Methods To Block Main Thread

What is the main thread? The main thread is where we create and start another thread from. Therefore, for our purpose, we can use the following methods from the Thread class. These methods make the Thread object join the main thread. As a result, the main thread has to wait for the other thread to complete.

To join threads to the main thread and make it make indefinitely, use the join method with no argument.

On the other hand, we can make the main thread wait only for several milliseconds.

We will use only these two methods for this post.

Java Codes To Block Main Method With Join

To start, consider the following codes. These Java codes use the join method with no argument to block the main thread. First, they create a Thread object that displays 1,000,000 UUID values and the number of milliseconds the operation took. With that amount of UUID values to generate, we expect the process would noticeably take time such that the program always displays “DONE” after “Invoking join method…” and other texts.

When we run the codes, we get the following results. However, the time may vary, but it is always more than one millisecond!

Now, suppose we want the main thread to wait for only one millisecond? See the following sample Java codes.

Join Method with waiting time Example

Using the following codes, we can force the main thread to only wait for a certain amount of time before execution. Therefore, another Java thread blocks the main thread only for a limited amount of time.

When we run the Java codes, they create another thread and only block the main method for 1 second.

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

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like