我正在研究线程连接()方法,我碰到了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