我们的老师给了我们以下代码:
public static void main(String[]args) {
Thread a = new Thread(new T(2));
Thread b = new Thread(new T(5));
a.start();
b.start();
try {
a.join(); //Thread a now runs completely to the end, before the main-method gets back to a "runnable" state
b.join(); //Thread b runs to death before the main methods u
} catch (InterruptedException ie) {}
System.out.println("done"); //Result: Random Thread a and b outputs
//and in the end "done" from main
}
public class T extends Thread {
private int nr;
public T(int nr) {
this.nr = nr;
}
public void run() {
for (int i=0; i<10; i++) {
System.out.println("Hello " + nr + " " + i);
}
}
线程 a 和 b 是相同的,并且都向控制台写入(在 for 循环中)10 个打印内容。 在 main 方法停止之前,线程 a 和 b 已完成,除了 main 方法之外,所有结果都是随机的。
我的问题是,如果您在一个线程上调用 join()
,它是否不应该阻塞其他线程(不仅仅是主线程)。他说, join() 只是卡住了 main 方法。但出于什么理由这应该是好的呢?他还说,这完全是随机的,由调度程序管理,在我看来,这对于这部分没有意义(调度程序命令线程状态,这很清楚,但至少在调用 join() 之后没有意义)不适用于java应用程序。或者我是假的?)。我的观点是,在主线程调用 join 方法之前,线程 a 和 b 完全运行到了最后。如果我理解正确的话,Javadoc 也告诉我同样的事情。
希望有人能给我一个答案。 :)
最佳答案
在 Thread
实例上对 join()
的调用只有在与该实例对应的线程终止后才会完成。
推论 1:如果该线程已经死亡,join()
立即返回。
推论 2:除当前线程外,没有其他线程受此调用影响。
He also said, that this is totally random and managed by the scheduler
你可能没有完全听懂老师在这里所说的内容。线程调度,这意味着决定何时为线程提供一些 CPU 时间来运行以及运行多少时间,由线程调度程序完成。它绝对不是“完全随机”,并且出于大多数实际考虑,所有线程始终运行。同样,这与 join
方法的行为关系不大。
关于java - join() 不会阻塞其他线程(主线程除外)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21906045/