我知道在一个线程内部调用join方法时,该线程必须等到加入Thread'终止。但如果在调用join()方法之前有更多代码 - 会发生什么?我在下面的代码中发布了我的代码和混淆:
class MyJoinThread extends Thread {
public static Thread myMain;
public void run() {
for(int i = 0; i< 2; i++) {
System.out.println("I am loop");
}
try {
myMain.join();
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
for(int j = 0; j < 5; j++) {
System.out.println("I am "+ Thread.currentThread().getName());
}
}
}
class MyJoinMainThread {
public static void main(String [] args) {
MyJoinThread.myMain = Thread.currentThread();
MyJoinThread th = new MyJoinThread();
th.start();
for(int i = 0; i<10; i++){
System.out.println("I am " + Thread.currentThread());
}
}
}
鉴于输出是:
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am loop
I am loop
I am Thread-0
I am Thread-0
I am Thread-0
I am Thread-0
I am Thread-0
为什么输出不是这样的?
I am loop
I am loop
I am Thread[main,5,main]
.....
I am Thread[main,5,main]
I am Thread-0
..
I am Thread-0
I am Thread-0
我在主线程上调用join()方法之前包含一个循环。为什么在主线程开始执行之前不会打印这些行?因为在调用join()方法之前调用了该循环。
答案 0 :(得分:1)
这是我在运行程序时获得的(每次运行后I am Thread[main,5,main]
和I am Thread[main,5,main]
I am loop
I am loop
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread[main,5,main]
I am Thread-0
I am Thread-0
I am Thread-0
I am Thread-0
I am Thread-0
的顺序会发生变化):
System.out.println("I am " + Thread.currentThread());
由于主线程中的System.out.println("I am loop");
与第二个线程中的telecomdata$predfpm1 <- predict(fpm1,type = "class")
FPM is an ordered logistic regression as presented below:
fpm1 <- clm(proposition ~ DMpropHigh + age + rel_length + education + gender + income + num_phones + arpu_index + calls_out_6_index + calls_in_6_index + calls_6_index + DM , data = telecomdata)
之间没有同步(并且没有发生 - 之前的关系https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/happens-before.html),因此在控制台中没有保证这些语句的顺序
实际的顺序取决于调度程序以及在PC上由JVM生成新线程需要多长时间。