java多執行緒 3 join的作用

2021-09-02 00:27:54 字數 1018 閱讀 8475

join()方法是thread類的乙個例項方法。它的作用是讓當前執行緒陷入「等待」狀態,等join的這個執行緒執行完成後,再繼續執行當前執行緒。

有時候,主線程建立並啟動了子執行緒,如果子執行緒中需要進行大量的耗時運算,主線程往往將早於子執行緒結束之前結束。

如果主線程想等待子執行緒執行完畢後,獲得子執行緒中的處理完的某個資料,就要用到join方法了。

如下:

package nsu.myllxy.multithread;

/** * 現在有t1、t2、t3三個執行緒,你怎樣保證t2在t1執行完後執行,t3在t2執行完後執行?

* @author nsu_zk

* @create 2019-08-07 20:04

*/public class joindemo

}});

final thread t2 = new thread(new runnable() catch (interruptedexception e) finally }}

});thread t3 = new thread(new runnable() catch (interruptedexception e) finally }}

});/* 依次啟動3個執行緒 */

t1.start();

t2.start();

t3.start();

}}

package nsu.myllxy.multithread;

/** * 所有子執行緒結束後才執行主線程

* * @author nsu_zk

* @create 2019-08-05 21:41

*/public class joindemo2 implements runnable

@override

public void run()

}public static void main(string args) throws interruptedexception

}

Java多執行緒 執行緒排程Join

public final void join throws interruptedexception 等待該執行緒終止。public final void join long millis throws interruptedexception 等待該執行緒終止的時間最長為 millis 毫秒。超時...

Java多執行緒 Join執行緒插隊

join 方法 waits for this thread to die.即 等待這個執行緒結束。1 程式中有兩個執行緒 執行緒a threada 執行緒b threadb 2 在 執行緒a 的run 方法中,呼叫了threadb.join 3 則 執行緒a 會在此段 出,暫停後續 的呼叫,等待 執...

Java多執行緒之join

1.join方法只有在繼承了thread類的執行緒中才有。2.執行緒必須要start 後再join才能起作用。將另外乙個執行緒join到當前執行緒,則需要等到join進來的執行緒執行完才會繼續執行當前執行緒。package thread.join class sleeper extends thre...