Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-10-31 02:31:29
Original
662 people have browsed it

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 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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!