How to add a thread and other threads in Java?

I have a main thread to start 10 other threads I want to finish the main thread only after all other threads stop So I should call join () on the other 10 threads before or after the start. For example:

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

So in the above example, I should call join () after start () or start (). Control returns the line number 9. > When executing the run method of any thread, the thread will die or remain active If possible, how to handle all threads when the run method completes means when control returns to the line number nine

Solution

Calling join () on a thread makes sense only after the thread is started The caller of join () will stop and wait for another thread to complete the operation it is executing So you might 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");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>