Java Thread join() Method
Example
Wait for a thread to finish before the program continues:
public class Main {
static class MyThread extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread();
thread.start();
thread.join();
System.out.println("The thread is finished");
}
}
Definition and Usage
The join() method makes the current thread wait until another thread is finished.
In the example, the main() method waits for thread to finish. Without join(), the two lines could be printed in any order, because the threads run at the same time.
Syntax
One of the following:
public final void join() throws InterruptedException
public final void join(long millis) throws InterruptedException
public final void join(long millis, int nanos) throws InterruptedException
Parameter Values
| Parameter | Description |
|---|---|
| millis | Optional. The longest time to wait, in milliseconds (thousandths of a second). 0 means wait until the thread is finished. |
| nanos | Optional. Extra nanoseconds (billionths of a second) to wait, from 0 to 999999. |
Technical Details
| Throws: | InterruptedException - if another thread interrupts the current thread while it waits. |
|---|
Related Pages
❮ Thread Methods