主線程等待子線程執(zhí)行完成后再執(zhí)行——Thread.join()

一养筒、一個例子

private static void joinTest(List<String> roles) {
Vector<Thread> vector = new Vector<>(10);
for (int i=0;i<10;i++){
MyThread myThread = new MyThread("id"+i,"name"+i,roles);
Thread t = new Thread(myThread);
vector.add(t);
t.start();
}
for (Thread thread : vector){
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class MyThread implements Runnable{

private String id;
private String name;
private List<String> roles;

public MyThread(String id,String name,List<String> roles){
    this.name = name;
    this.id = id;
    this.roles = roles;
}

@Override
public void run() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    roles.add(name);
    System.out.println("執(zhí)行了-id:"+id+"name:"+name+"roles size:"+roles.size());
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public List<String> getRoles() {
    return roles;
}

public void setRoles(List<String> roles) {
    this.roles = roles;
}

}
輸出結(jié)果:

開始:1515250426924
執(zhí)行了-id:id2name:name2roles size:1
執(zhí)行了-id:id1name:name1roles size:3
執(zhí)行了-id:id0name:name0roles size:2
執(zhí)行了-id:id4name:name4roles size:4
執(zhí)行了-id:id6name:name6roles size:7
執(zhí)行了-id:id7name:name7roles size:8
執(zhí)行了-id:id8name:name8roles size:9
執(zhí)行了-id:id5name:name5roles size:6
執(zhí)行了-id:id3name:name3roles size:5
執(zhí)行了-id:id9name:name9roles size:10
[name2, name0, name1, name4, name3, name5, name6, name7, name8, name9]
結(jié)束:1515250427932耗時:1008roles size:10
可以看出斑鸦,上面每個線程執(zhí)行1000ms,總時長1008ms.

二问慎、源碼分析

/**

  • Waits for this thread to die.
  • <p> An invocation of this method behaves in exactly the same
  • way as the invocation
  • <blockquote>
  • {@linkplain #join(long) join}{@code (0)}
  • </blockquote>
  • @throws InterruptedException
  •      if any thread has interrupted the current thread. The
    
  •      <i>interrupted status</i> of the current thread is
    
  •      cleared when this exception is thrown.
    

*/
public final void join() throws InterruptedException {
join(0);
}
這里看清楚一點:join傳參為0。

然后進入join方法:

/**

  • Waits at most {@code millis} milliseconds for this thread to
  • die. A timeout of {@code 0} means to wait forever.
  • <p> 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
    
  •      <i>interrupted status</i> of the current thread is
    
  •      cleared when this exception is thrown.
    

*/
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) {
    while (isAlive()) {
        wait(0);
    }
} else {
    while (isAlive()) {
        long delay = millis - now;
        if (delay <= 0) {
            break;
        }
        wait(delay);
        now = System.currentTimeMillis() - base;
    }
}

}
從源碼可以看出赴背,如果線程被生成了,但還未被起動,isAlive()將返回false楞遏,調(diào)用它的join()方法是沒有作用的茬暇,將直接繼續(xù)向下執(zhí)行wait。而wait方法中有參數(shù)寡喝,也就是不用喚醒誰糙俗,只是不再執(zhí)行wait,向下繼續(xù)執(zhí)行而已预鬓。

三巧骚、join總結(jié)

join方法的原理就是調(diào)用相應(yīng)線程的wait方法進行等待操作的,例如A線程中調(diào)用了B線程的join方法格二,則相當(dāng)于在A線程中調(diào)用了B線程的wait方法劈彪,當(dāng)B線程執(zhí)行完(或者到達等待時間),B線程會自動調(diào)用自身的notifyAll方法喚醒A線程顶猜,從而達到同步的目的沧奴。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市驶兜,隨后出現(xiàn)的幾起案子扼仲,更是在濱河造成了極大的恐慌,老刑警劉巖抄淑,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件屠凶,死亡現(xiàn)場離奇詭異,居然都是意外死亡肆资,警方通過查閱死者的電腦和手機矗愧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來郑原,“玉大人唉韭,你說我怎么就攤上這事》咐纾” “怎么了属愤?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長酸役。 經(jīng)常有香客問我住诸,道長,這世上最難降的妖魔是什么涣澡? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任贱呐,我火速辦了婚禮,結(jié)果婚禮上入桂,老公的妹妹穿的比我還像新娘奄薇。我一直安慰自己,他們只是感情好抗愁,可當(dāng)我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布馁蒂。 她就那樣靜靜地躺著呵晚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪远搪。 梳的紋絲不亂的頭發(fā)上劣纲,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天,我揣著相機與錄音谁鳍,去河邊找鬼癞季。 笑死,一個胖子當(dāng)著我的面吹牛倘潜,可吹牛的內(nèi)容都是我干的绷柒。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼涮因,長吁一口氣:“原來是場噩夢啊……” “哼废睦!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起养泡,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤嗜湃,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后澜掩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體购披,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年肩榕,在試婚紗的時候發(fā)現(xiàn)自己被綠了刚陡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡株汉,死狀恐怖筐乳,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情乔妈,我是刑警寧澤蝙云,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站路召,受9級特大地震影響贮懈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜优训,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望各聘。 院中可真熱鬧揣非,春花似錦、人聲如沸躲因。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至搞监,卻和暖如春水孩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背琐驴。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工俘种, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人绝淡。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓宙刘,卻偏偏與公主長得像,于是被迫代替她去往敵國和親牢酵。 傳聞我的和親對象是個殘疾皇子悬包,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,914評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 文章來源:http://www.54tianzhisheng.cn/2017/06/04/Java-Thread/...
    beneke閱讀 1,486評論 0 1
  • 本文主要講了java中多線程的使用方法、線程同步馍乙、線程數(shù)據(jù)傳遞布近、線程狀態(tài)及相應(yīng)的一些線程函數(shù)用法、概述等丝格。 首先講...
    李欣陽閱讀 2,454評論 1 15
  • Java多線程學(xué)習(xí) [-] 一擴展javalangThread類 二實現(xiàn)javalangRunnable接口 三T...
    影馳閱讀 2,957評論 1 18
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法撑瞧,類相關(guān)的語法,內(nèi)部類的語法铁追,繼承相關(guān)的語法季蚂,異常的語法,線程的語...
    子非魚_t_閱讀 31,631評論 18 399
  • 主題:應(yīng)對批評 本片段來自《談話的力量》 圖書介紹: 《談話的力量》已經(jīng)成為全世界最受歡迎的教授談話技巧的圖書琅束。多...
    穎噠噠閱讀 102評論 3 1