我有以下代碼試圖undersatand join()方法
class Multi extends Thread{
public void run(){
for(int i=1;i<=3;i++){
System.out.println(i + ": "+Thread.currentThread().getName());
}
}
public static void main(String args[]){
Multi t1=new Multi();
t1.setName("First Thread");
Multi t2=new Multi();
t2.setName("Second Thread");
Multi t3=new Multi();
t3.setName("Third Thread");
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){System.out.println(e);}
t3.start();
}
}
**
的輸出有所不同每次運行時間:
1st time Output
1: Second Thread
2: Second Thread
3: Second Thread
1: First Thread
2: First Thread
3: First Thread
1: Third Thread
2: Third Thread
3: Third Thread
=============================================
2nd time Output
1: First Thread
2: First Thread
3: First Thread
1: Second Thread
2: Second Thread
3: Second Thread
1: Third Thread
2: Third Thread
3: Third Thread
*************************************************
由於t2.join()
t1.join()
如何後調用第一個輸出來了嗎? t2
是否應該等待t1
執行?
請幫助我瞭解join()
法的行爲,如果可能的話有更多的代碼片段的例子
爲了得到你期望的行爲,你需要在*'t1.join()之後調用't2.start()'*。在你當前的代碼中,兩個線程並行運行。 – assylias
感謝您的編輯:)我正要這樣做 –