本文內容大多基於官方文檔和網上前輩經驗總結,經過個人實踐加以整理積累,僅供參考。
join() 方法是 java.lang.Thread 類的執行個體方法,方法簽名
public final void join() throws InterruptedException
public final void join(long millis) throws InterruptedException
public final void join(long millis, int nanos) throws InterruptedException
join() 方法使得一個線程在另一個線程結束後再執行,如果在一個線程執行個體上調用,當前啟動並執行線程將阻塞直至調用 join() 方法的線程執行個體結束
join() 方法接收 long 型別參數,使得在等待特定毫秒後線程失效
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
join() 方法還可以額外接收一個 int 型別參數
Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
樣本:
public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("First thread started!"); System.out.println("Ready to sleep 5 seconds!"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("First thread ended!"); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { System.out.println("Second thread started!"); System.out.println("Second thread ended!"); } }); t1.start(); t1.join(); t2.start();}
如果注釋掉 t1.join();,運行結果:
去掉注釋後運行結果:
給 join() 方法傳入一個 long 型別參數,使得最長等待 3 秒
public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("First thread started!"); System.out.println("Ready to sleep 5 seconds!"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("First thread ended!"); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { System.out.println("Second thread started!"); System.out.println("Second thread ended!"); } }); t1.start(); t1.join(3000); t2.start();}
運行結果: