如何在java中加入一个线程与其他线程? [英] How to join one thread with other in java?

查看:432
本文介绍了如何在java中加入一个线程与其他线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主线程启动10个其他线程。我希望只有在所有其他线程停止后才能完成主线程。所以我应该在开始之前或启动之后在其他10个线程上调用join()。例如:

I have one main thread that starts 10 other threads. I want that the main thread will be finished only after all other threads stopped. So should I call join() on other 10 threads before starting or after starting them. For instance:

// 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




  1. 所以在上面的例子中,我应该调用join()在start()之前或start()之后。

  2. 控件是否会返回到行号。只有在所有线程都完成后才会出现。

  3. 当执行任何线程的run方法时,该线程将死亡或保持活动状态。如果愿意的话,当run方法完成时如何处理所有线程意味着当控制返回到行号时。 9


推荐答案

致电加入()在一个线程上只有在线程启动后才有意义。 join()的调用者将停止并等待另一个线程完成它正在执行的操作。所以你可能想这样做:

Calling join() on a thread only makes sense after the thread is started. The caller of join() will stop and wait until the other thread finishes what it's doing. So you may want to do this:

// 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");

这篇关于如何在java中加入一个线程与其他线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆