Understanding Thread.join in Java

UPDATED: 29 August 2016

Thread.join()
Waits for this thread to die.

Thread.join(long millis)
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
Thread.join() and Thread.join(long millis) explained with real world example in Image.

Source code (MessageThread.java)
/**
 * Thread that prints message in interval of 4 seconds.
 *
 * @author javaQuery
 * @date 29th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class MessageThread implements Runnable {

    // Display a message, preceded by
    // the name of the current thread
    static void threadMessage(String message) {
        String threadName = Thread.currentThread().getName();
        System.out.format("%s: %s%n", threadName, message);
    }

    @Override
    public void run() {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };
        try {
            for (int i = 0; i < importantInfo.length; i++) {
                // Pause for 4 seconds
                Thread.sleep(4000);
                // Print a message
                threadMessage(importantInfo[i]);
            }
        } catch (InterruptedException e) {
            threadMessage("I wasn't done!");
        }
    }
}

Source code (ThreadJoinExample.java)
/**
 * Thread join example.
 * @author javaQuery
 * @date 29th August, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ThreadJoinExample {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new MessageThread());
        // start MessageThread.
        t.start();
        /**
         * Main Thread (ThreadJoinExample) will wait for 't' to finish 
         * its task in 5 seconds of it will leave.
         */
        t.join(5000);
        
        /**
         * Main Thread (ThreadJoinExample) will wait until 't' finish its task.
         */
        // t.join(); 
        System.out.println("Main Thread left(finish).");
    }
}

Output
Thread-0: Mares eat oats
Main Thread left(finish).
Thread-0: Does eat oats
Thread-0: Little lambs eat ivy
Thread-0: A kid will eat ivy too

0 comments :