在Thread類的Api中,Join的作用是讓當前線程等待目標線程結束之后才繼續執行。
thread.Join把指定的線程加入到當前線程,可以將兩個交替執行的線程合並為順序執行的線程。
比如在線程B中調用了線程A的Join()方法,直到線程A執行完畢后,才會繼續執行線程B。
想要更深入了解,建議看一下join的源碼,也很簡單的,使用wait方法實現的。t.join(); //調用join方法,等待線程t執行完畢
t.join(1000); //等待 t 線程,等待時間是1000毫秒。
分別是
public final synchronized void join(long millis, int nanos); //使當前線程等待目標線程millis 毫秒 ,nanos納秒之后,當前線程繼續執行。
public final synchronized void join(long millis); //使當前線程等待目標線程millis 毫秒,當前線程繼續執行。
public final void join(); //使當前線程時刻檢測目標線程,直到目標線程執行完成,再執行當前線程。
下面我們主要查看下 public final synchronized void join(long millis) 的源碼:
public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) {
//如果等待的毫秒數為0,則通過Api, isAlive()時刻檢測目標線程是否存活,若存活則繼續等待。 while (isAlive()) { wait(0); } } else { while (isAlive()) {
//判斷目標線程是否存活,若存活,則等待mills毫秒,然后跳出join,當前線程執行。 long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }
從源碼可以看出,就是當前線程在判斷目標線程是否存活,如果存活根據參數的值,是無限等待到目標線程結束才執行當前線程,還是執行一段時間就開始執行當前線程。
public final void join();底層調用Join(0);實現無限等待知道目標線程結束。
下面再編寫一個demo,先執行線程1,再執行線程2,最后執行線程3;
package com.dsx.thread; public class TestThreadJoin { public static void ThreadCreate(){ final Thread t1 = new Thread(new Runnable() { public void run() { System.out.println("線程1執行了。。。"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }); final Thread t2 = new Thread(new Runnable() { public void run() { try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("線程2執行了。。。。。"); } }); Thread t3 = new Thread(new Runnable() { public void run() { try { t2.join(); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("線程3執行了。。。。。。。"); } }); t3.start(); t2.start(); t1.start(); } public static void main(String[] args) { ThreadCreate(); } }