我正在研究線程連接()方法,我碰到了stackoverflow上的ThreadJoinMethod後 。我修改了代碼來開發一個工作示例,我對 輸出感到困惑。代碼片段是。線程連接()方法輸出混淆
class JoinRunnable implements Runnable{
public void run() {
for(int i =0 ; i < 4 ; i++){
System.out.println(i);
}
}
}
public class TestJoin{
public static void main(String[] args) throws InterruptedException {
JoinRunnable joinRunnable = new JoinRunnable();
Thread t1 = new Thread(joinRunnable);
Thread t2 = new Thread(joinRunnable);
t1.start();
t2.start();
System.out.println("Currently running thread: " + Thread.currentThread().getName());
t1.join();
t2.join();
System.out.println("I must wait");
}
}
以下程序的輸出是: -
0
1
2
3
0
1
2
3
Currently running thread: main
I must wait
我在輸出困惑。當前線程將在t1 和t2上調用join
後加入,但爲什麼在t1和t2 完成後語句"Currently Running Thread: main"
正在打印?我在這裏錯過了一些重要的概念嗎?因爲main()會在 之後加入t1和t2之前的連接語句。有人可以詳細說明嗎?
其他兩個線程是否可能在調用'Thread','System','out'等各個庫之前調用它們的過程來產生結果?測試,通過爲每個人輸出1到10000,然後通過篩選獲得樂趣。 – christopher
在循環迭代中添加睡眠,您將看到不會得到相同的結果。 –
完美,我剛剛添加睡眠現在正在運行的方法main被首先打印。所以輸出必須不同。萬分感謝。 – benz