English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
java.lang.ThreadThe class provides a methodjoin()
, which can be used in its overloaded version to achieve the following purposes.
join() -The current thread calls this method on the second thread, causing the current thread to block until the second thread terminates.
join(long millisec) -The current thread calls this method on the second thread, causing the current thread to block until the second thread terminates or the specified milliseconds.
join(long millisec, int nanos) -The current thread calls this method on the second thread, causing the current thread to block until the second thread terminates or the specified milliseconds+up to nanoseconds.
Please refer to the following example to demonstrate this concept.
class CustomThread implements Runnable { public void run() { System.out.println(Thread.currentThread().getName() + " started."); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " interrupted."); } System.out.println(Thread.currentThread().getName() + " exited."); } } public class Tester { public static void main(String args[]) throws InterruptedException { Thread t1 = new Thread(new CustomThread(), "Thread-1"); t1.start(); //The main thread class is in t1the connection on //Once t1completed, then only t2can start t1.join(); Thread t2 = new Thread(new CustomThread(), "Thread-2"); t2.start(); //The main thread class is in t2the connection //Once t2completed, then only t3can start t2.join(); Thread t3 = new Thread(new CustomThread(), "Thread-3"); t3.start(); } }
Output Result
Thread-1 started. Thread-1 exited. Thread-2 started. Thread-2 exited. Thread-3 started. Thread-3 exited.