標籤:throws start ack lis param loop public recommend 父類
以下面例子說明下面的源碼:main 線程 和 A線程,A線程是main線程建立並且啟動的,main線程優先順序比較高,正在執行;
這個時候main線程調用A.join()之後,main線程一直等待,直到A線程運行完畢,main線程才運行。
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) {
//A線程是start,在運行中 while (isAlive()) {
//main線程等待 wait(0); } } else {
//join(timeOut)的情況 while (isAlive()) {
//根據當前timeout的時間-now 是否<=0進行判斷,主線程是否繼續阻塞等待 long delay = millis - now;
//等待逾時時間到了,則主線程不阻塞了,等待結束 if (delay <= 0) { break; } wait(delay);
//子線程從迴圈開始到現在啟動並執行時間 now = System.currentTimeMillis() - base; } } }
給一個例子來理解:
package concurrentMy.joins;/** * * @author Administrator * * main 線程 和 A線程,A線程是main線程建立並且啟動的,main線程優先順序比較高,正在執行; * 這個時候main線程調用A.join()之後,main線程一直等待,直到A線程運行完畢,main線程才運行 * */class ThreadA extends Thread { public ThreadA(String name){ super(name); } @Override public void run() { for (int i = 0; i < 20; i++) { // 複寫父類的toString方法, 返回該線程的字串表示形式,包括線程名稱、優先順序和線程組。 System.out.println(Thread.currentThread().getName() + "-" + i); } }}public class JoinDemo { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { ThreadA A = new ThreadA("線程A"); A.start(); A.join(); //A線程加入到“main線程”中,main線程一直等待,直到A線程執行完畢,main線程才運行 System.out.println(Thread.currentThread().getName() + "執行"); System.out.println(Thread.currentThread().getName() + "執行終止"); }}
輸出結果:
線程A-0線程A-1線程A-2線程A-3線程A-4線程A-5線程A-6線程A-7線程A-8線程A-9線程A-10線程A-11線程A-12線程A-13線程A-14線程A-15線程A-16線程A-17線程A-18線程A-19main執行main執行終止
代碼運行整個過程說明入:
java基礎知識回顧之java Thread類學習(十一)--join方法的理解