加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何在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().
>控件是否会返回到行号.只有在所有线程完成后才能使用9.
>当执行任何线程的run方法时,该线程将死亡还是保持活动状态.如果可以的话,当run方法完成时如何处理所有线程意味着当控制返回到行号时. 9

解决方法

在线程上调用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");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读