java的join方法 [英] java join method
问题描述
在以下情况下,我无法理解join的含义:
I have problem understanding the meaning of join in the following case:
Thread t1=new MyThread(1);
Thread t2=new MyThread(2);
t1.start();
t2.start();
t1.join();
t2.join();
问题是: 据我了解,start调用Thread的run方法. 因此主线程首先经过启动,因此所有线程都被初始化. 然后主线程转到t1.join,这意味着主线程将等到t1结束其运行,然后才继续到t2.join(). 我不了解的是t1,t2同时已经开始,所以它们在run方法中. 因此结果应该是出乎意料的.我对吗? 那么为什么会依次出现: 我有以下运行方法:
the question is: as I understand start calls the run method of the Thread. so the main thread first goes over the starts and thus all threads are initialized. then the main thread goes to t1.join and that means that the main thread will wait till t1 to end his running and only then continues to t2.join(). What I don't understand is the t1,t2 meanwhile already started so they are inside the run method. and thus the result supposed to be unexpected. am I right? so why does it come out in order: I have the following run method:
void run(){
for(int i=0; i<4; i++){
System.out.println(j);
}
}
当j是MyThread构造函数中的标识符时; 输出为:
when j is the identifier in the MyThread constructor; the output is:
2 2个 2个 2个 1个 1个 1个 1
2 2 2 2 1 1 1 1
或 1个 1个 1个 1个 2个 2个 2个 2
or 1 1 1 1 2 2 2 2
推荐答案
如果在执行thread_2
时也加入了thread_1
并且在thread_1
之前终止,那么thread_2.join()
将不起作用,并且当前线程将继续执行.是的,您不能期望任何可预测的执行流程.
If you join thread_1
while thread_2
is executed too and terminates before thread_1
does, then thread_2.join()
won't give any effect and the current thread will continue execution. And yes, you can't expect any predictable execution flow.
这篇关于java的join方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!