Waiting for Completion of Multiple Threaded Processes
In this code snippet, you have multiple threads created, each running a task within its own thread of execution. To ensure that the main thread waits for all the sub-threads to complete their execution before proceeding, you can implement the following approach:
<code class="java">// ... (code as before) public class DoSomethingInAThread implements Runnable { public static void main(String[] args) { Thread[] threads = new Thread[1000]; // Assume 1000 threads for example // Start all threads for (int n = 0; n < 1000; n++) { threads[n] = new Thread(new DoSomethingInAThread()); threads[n].start(); } // Wait for all threads to complete for (int i = 0; i < threads.length; i++) { threads[i].join(); } } public void run() { // ... (code as before) } }</code>
By using the join() method, the main thread blocks until all sub-threads have completed their execution, ensuring that your program waits for all tasks to finish before proceeding with the code that follows the loop. This approach gives you control and ensures that resources are released and the program terminates correctly.
The above is the detailed content of How to Ensure the Main Thread Waits for Completion of Multiple Threaded Processes?. For more information, please follow other related articles on the PHP Chinese website!