我有一个主线程启动其他 10 个线程。我希望只有在所有其他线程停止后主线程才会完成。那么我应该在其他 10 个线程启动之前或启动之后调用 join() 吗?例如:
// in the main() method of Main thread
Thread [] threads = new Thread[10];
for(int i = 0; i < 10; i++) {
// ParserThread() is a runnable thread
threads[i] = new Thread(new ParserThread());
threads[i].join();
threads[i].start();
}
System.out.println("All threads have been finished"); // line no. 9
- 就像上面的例子一样,我应该在start()之前还是start()之后调用join()。
- 控件会返回到第 1 行吗? 9 仅在所有线程完成后。
- 当任何线程的run方法被执行后,该线程将死亡或保持活动状态。如果会的话,当它们的 run 方法完成时如何终止所有线程意味着当控制返回到第 1 行时。 9
Calling join()
在线程上才有意义after线程已启动。来电者为join()
将停止并等待,直到另一个线程完成它正在做的事情。所以你可能想要这样做:
// in the main() method of Main thread
Thread [] threads = new Thread[10];
for(int i = 0; i < 10; i++) {
// ParserThread() is a runnable thread
threads[i] = new Thread(new ParserThread());
threads[i].start();
}
System.out.println("All threads have been started");
for(int i = 0; i < 10; i++) {
threads[i].join();
}
System.out.println("All threads have been finished");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)