執行緒間通訊_等待/通知之Thread.join()

z1340954953發表於2018-04-24

Thread.join

原始碼:

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;
            }
        }
    }

從原始碼可以看出,只要執行緒是alive的,就一直呼叫wait方法,直到執行緒終止。也就是如果在一個執行緒中,啟動了另一個執行緒,並呼叫該執行緒的wait方法,那麼當前執行緒就會阻塞,知道另一個執行緒執行完畢,才去向下執行.

簡單表示:

Thread1{

run{

thread2.start();
thread2.join();
System.out.print("上面執行緒執行完畢,我才繼續執行,沒有執行完,我就阻塞")

}

}

程式碼驗證:

package com.ftf.thread.test;

public class ThreadJoinDemo {
	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new Runnable() {
			public void run() {
				System.out.println("執行緒0執行...end...");
			}
		});
		t.start();
		for (int i = 0; i < 10; i++) {
			JoinThread jt = new JoinThread(t, i);
			jt.start();
			t = jt;
		}
	}
}

class JoinThread extends Thread {
	private Thread t;
	private int i;

	public JoinThread(Thread t, int i) {
		this.t = t;
		this.i = i;
	}

	@Override
	public void run() {
		try {
			t.join();
			System.out.println("執行緒" + (i + 1) + "執行....end...");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

列印結果:

執行緒0執行...end...
執行緒1執行....end...
執行緒2執行....end...
執行緒3執行....end...
執行緒4執行....end...
執行緒5執行....end...
執行緒6執行....end...
執行緒7執行....end...
執行緒8執行....end...
執行緒9執行....end...
執行緒10執行....end...


相關文章