如何在java中加入一个线程与其他线程?
发布时间:2020-12-15 05:18:56 所属栏目:Java 来源:网络整理
导读:我有一个主线程启动10个其他线程.我希望只有在所有其他线程停止后才能完成主线程.所以我应该在开始之前或之后调用其他10个线程上的join().例如: // in the main() method of Main threadThread [] threads = new Thread[10];for(int i = 0; i 10; i++) { //
我有一个主线程启动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(). 解决方法
在线程上调用join()只在线程启动后才有意义. 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"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |