Thread Join Method Tutorial

In this tutorial I will demonstrate how to use the join() method. When the join() method is invoked on a child thread, the main thread is placed into one of the following states: WAITING or TIMED_WAITING. When the main thread is in the state of WAITING, it will not execute any more statements until the child thread has terminated. When the main thread is in the state of TIMED_ WAITING, it will not execute any move statements until the child thread has terminated or a certain number of milliseconds have passed. There are three overloaded versions of the join() method:
void join() causes the main thread state to change to WAITING
void join(long milliseconds) causes the main thread state to change to TIMED_WAITING for a certain number of milliseconds.
void join(long milliseconds, int nanoseconds) causes the main thread state to change to TIMED_WAITING for a certain number of milliseconds plus nanoseconds - now that is some precision!!!

Because of the way the join() method changes the behavior of thread states, it is perfect opportunity to demonstrate every thread states except BLOCKED.

  • NEW - A thread has been declared, but has not yet started is in this state.
  • RUNNABLE - In this state a thread is executing in the JVM.
  • BLOCKED - In this state a thread is blocked waiting for a monitor lock or intrinsic lock. I'll explain in later down the road.
  • WAITING - A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
  • TIMED WAITING - A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
  • TERMINATED - A thread that has exited is in this state.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md ThreadJoin
C:\Java>cd ThreadJoin
C:\Java\ThreadJoin>Notepad ThreadJoin.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.util.*;
class ThreadJoin {
    protected static Thread mainThread = Thread.currentThread();;

    public static void main(String args[]) {
        System.out.println("Calculating primes: ");
        System.out.println("Main thread state: " + ThreadJoin.mainThread.getState());
        try {
            for (long x = 6223372036854775799L; x <= 6223372036854775999L; x+=2) {
                new MyCalculations(x).join();
                System.out.println("Inside Main Method For Loop, Main thread state = " + ThreadJoin.mainThread.getState());
                System.out.println("Active threads: " + Thread.activeCount());
                System.out.println("\n-------------------\n");
            }
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted");
        }
        System.out.println("Ending main method.");
    }
}

class MyCalculations extends Thread {
    private long numberToFactor = 0;

    MyCalculations(long numberToFactor){
        this.numberToFactor = numberToFactor;
        System.out.println("MyCalculations constructor, before start(), state = " + this.getState());
        start();
        System.out.println("MyCalculations constructor, after start(), state = " + this.getState());
    }

    @Override
    public void run() { // this is where the new thread starts
        isItPrime(numberToFactor);
        System.out.println("Inside MyCalculations run(), Main thread state = " + ThreadJoin.mainThread.getState());
    }

    void isItPrime(long numberToFactor) { 
        if (numberToFactor % 2 == 0) {
            System.out.println(numberToFactor + " is NOT Prime ... divisible by 2");
            return;
        }

        long squareRoot = (long) Math.sqrt(numberToFactor);
        for (long i = 3; i <= squareRoot; i+=2) {
            if (numberToFactor % i == 0) { // when the remainder is 0 the number is evenly divisible - hence not prime
                System.out.println(numberToFactor + " is NOT Prime ... first divisible by " + i);
                return;
            }
        }
        System.out.println(numberToFactor + " is Prime!!!");
    }
}

Now switch back to the command prompt (CMD) and type in javac ThreadJoin.java and press Enter.
Now type in java ThreadJoin and press Enter.


C:\Java\ThreadJoin>javac ThreadJoin.java
C:\Java\ThreadJoin>java ThreadJoin
see video for results


Final thoughts

The way the join() methods works is really straight forward. You should now have a clear understanding of every thread state except for BLOCKING ... I'll demonstrate how that one works in a future tutorial.


Tutorials