join 可以安排先後順序了.如果要先完成t1, 再運行t2, 最近運行t3,就可以這樣了
t1.start();
t1.join();
t2.start();
t2.join();
t3.start()
JDK是這樣說的:
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
等待一段時間直到這個線程死亡
public class ThreadTest implements Runnable {<br />public static int a = 0;<br />public void run() {<br />for (int k = 0; k < 5; k++) {<br />a = a + 1;<br />}<br />}<br />public static void main(String[] args) throws Exception {<br />Runnable r = new ThreadTest();<br />Thread t = new Thread(r);<br />t.start();<br />System.out.println(a);<br />}<br />}
請問程式的輸出結果是5嗎?答案是:有可能。這個時候main線程和t線程是並列啟動並執行。
怎樣才能讓輸出結果為5!其實很簡單,join() 方法提供了這種功能。join() 方法,它能夠使調用該方法的線程在此之前執行完畢。
public class ThreadTest implements Runnable {<br />public static int a = 0;<br />public void run() {<br />for (int k = 0; k < 5; k++) {<br />a = a + 1;<br />}<br />}<br />public static void main(String[] args) throws Exception {<br />Runnable r = new ThreadTest();<br />Thread t = new Thread(r);<br />t.start();<br />t.join();<br />System.out.println(a);<br />}<br />}
這個時候,程式輸入結果始終為5。
public final void join() throws InterruptedException {<br />join(0);<br />}
就是說如果是t.join() = t.join(0) 0 JDK這樣說的 A timeout of 0 means to wait forever 字面意思是永遠等待,其實是等到t結束後。
這個是怎麼實現的嗎? 看JDK代碼:
/**<br />* Waits at most <code>millis</code> milliseconds for this thread to<br />* die. A timeout of <code>0</code> means to wait forever.<br />*<br />* @param millis the time to wait in milliseconds.<br />* @exception InterruptedException if any thread has interrupted<br />* the current thread. The <i>interrupted status</i> of the<br />* current thread is cleared when this exception is thrown.<br />*/<br />public final synchronized void join(long millis)<br />throws InterruptedException {<br />long base = System.currentTimeMillis();<br />long now = 0;<br />if (millis < 0) {<br />throw new IllegalArgumentException("timeout value is negative");<br />}<br />if (millis == 0) {<br />while (isAlive()) {<br />wait(0);<br />}<br />} else {<br />while (isAlive()) {<br />long delay = millis - now;<br />if (delay <= 0) {<br />break;<br />}<br />wait(delay);<br />now = System.currentTimeMillis() - base;<br />}<br />}<br />}
其實Join方法實現是通過wait。
wait()方法
在其他線程調用對象的wait方法後,導致當前線程等待。線程會釋放掉它所佔有的“鎖標誌”,從而使別的線程有機會搶佔該鎖。
當main線程調用t.join時候,main線程會失去線程對象t的鎖,進入等待,直到該對象喚醒main線程,比如退出後。