Home » Java Thread join() Method with Examples

Java Thread join() Method with Examples

by Online Tutorials Library

Java Thread join() method

The join() method of thread class waits for a thread to die. It is used when you want one thread to wait for completion of another. This process is like a relay race where the second runner waits until the first runner comes and hand over the flag to him.

Syntax

Parameter

Return

Exception

IllegalArgumentException: This exception throws if the value of millis is negative, or the value of nanos is not in the range 0-999999

InterruptedException: This exception throws if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

Example 1

Test it Now

Output:

1  2  3  4  1  1  2  2  3  3  4  4  

In the above example 1, when t1 completes its task then t2 and t3 starts execution.

Example 2

Test it Now

Output:

1  2  3  1  1  4  2  2  5  3  3  4  4  5  5  

In the above example 2, when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing.

You may also like