"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Ensure the Main Thread Waits for Completion of Multiple Threaded Processes?

How to Ensure the Main Thread Waits for Completion of Multiple Threaded Processes?

Published on 2024-11-11
Browse:697

How to Ensure the Main Thread Waits for Completion of Multiple Threaded Processes?

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:

  1. Store Threads in an Array: Create an array to store all the created threads. This ensures organized tracking of their completion status.
  2. Start All Threads: Loop through the threads array and start each thread using the start() method.
  3. Join Threads in a Loop: After starting all the threads, add a loop to join each thread in the array. The join() method blocks the calling thread (in this case, the main thread) until the target thread completes its execution.
// ... (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 

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3