Java Thread Join Example

Last updated on March 15th, 2017 at 12:08 pm

Previous
Next

Thread class’s join method can be used to stop current execution of thread until thread it joins, completes its task. So basically , it waits for the thread on which join method is getting called, to die.

There are three variant of join method:

public final void join() throws InterruptedException :

Thread on which join method is getting called to die.

public final void join(long millis) throws InterruptedException:
This method when called on the thread, it waits for either of following:

  • Thread on which join method is getting called, to die.
  • Specified milliseconds
public final void join(long millis,int nanos) throws InterruptedException:
This method when called on the thread, it waits for either of following:
  • Thread on which join method is getting called, to die.
  • Specified milliseconds + nano seconds

Example:

Lets take simple example:

Create ThreadExampleMain.java

When you run above program, you will get following output.

Lets analysis output now.

  1. Main thread execution starts
  2. Thread 1 starts(Thread 1 start) and as we have put t1.join() , it will wait for t1 to die(Thread 1 end).
  3. Thread 2 starts(Thread 2 start) and waits for either 1 seconds or die but as we have put sleep for 4 seconds in run method, it will not die in 1 second. so main thread resumes and Thread 3 starts(Thread 3 start)
  4. As we have put t2.join() and t3.join(). These 2 threads will get completed before exiting main thread.So Thread 2 will end(Thread 2 end ) and then thread 3 will end(Thread 3 end).
  5. Main thread execution ends.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog