在逛論壇的時候發現這樣一個問題:
Thread tt = new Thread(new HelloRunnable());
tt.start();
tt.join();
既然java中join是讓當前線程等待線程tt終止,然後再繼續執行當前線程,那麼,爲什麼還要生成thread tt幹嗎呢,不直接全在當前線程裏順序執行?效果不是一樣?
比如有兩個線程一個是主線程,另一個是我們定義的線程,我們定義的線程的操作可能比較耗時,當我們的主線程操作處理完成後,需要用到定義線程的結果時,這時就要用到join()方法了。
Thread tt = new Thread(new HelloRunnable());
tt.start();
//執行當前線程的一些操作,和tt線程並行運行
tt.join();
//當前線程後面的操作需要用到tt運行產生的結果,因此,前面調用join方法使得tt線程等待
join方法的另一個實例:
/**
* 測試join()
*
* @author mooner
*
*/
public class JoinThreadTest implements Runnable {
private static int a = 1;
public void run() {
System.out.println(Thread.currentThread().getName());
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) throws InterruptedException {
JoinThreadTest j = new JoinThreadTest();
Thread t = new Thread(j);
t.start();
t.join();
System.out.println("main");
}
}
結果如下:
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
main