Published:
Description
The java.lang.Thread.join() method waits for this thread to die.
Declaration
Following is the declaration for java.lang.Thread.join() method
public final void join() throws InterruptedException
Parameters
NA
Return Value
This method does not return any value.
Exception
InterruptedException − if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
Example
import java.lang.*;
public class ThreadDemo implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}
public static void main(String args[]) throws Exception {
Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();
// waits for this thread to die
t.join();
System.out.print(t.getName());
//checks if this thread is alive
System.out.println(", status = " + t.isAlive());
}
}
Output -
Thread-0, status = true
Thread-0, status = false
join method with time arguments
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* interrupted status of the current thread is
* cleared when this exception is thrown.
*/
public final synchronized void join(long millis)