How do I pause main() until all other threads have died?

后端 未结 9 893
无人及你
无人及你 2020-12-31 00:46

In my program, I am creating several threads in the main() method. The last line in the main method is a call to System.out.println(), which I don\'t want to call until all

相关标签:
9条回答
  • 2020-12-31 01:12

    You start your threads and immediately wait for them to be finished (using join()). Instead, you should do the join() outside of the for-loop in another for-loop, e.g.:

    // start all threads
    for(int i=0; i<numberOfRaceCars; i++) {
        racecars[i].start();
    }
    // threads run... we could yield explicity to allow the other threads to execute
    // before we move on, all threads have to finish
    for(int i=0; i<numberOfRaceCars; i++) {
        racecars[i].join(); // TODO Exception handling
    }
    // now we can print
    System.out.println("It's over!");
    
    0 讨论(0)
  • 2020-12-31 01:14

    You have better options if you go for ExecutorService or ThreadPoolExecutor framework.

    1. invokeAll

      Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress. Type Parameters:

    2. CountDownLatch : Initialize CountDownLatch with counter as number of threads. Use countDown() and await() APIs and wait for counter to become zero.

    Further references:

    How to use invokeAll() to let all thread pool do their task?

    How is CountDownLatch used in Java Multithreading?

    0 讨论(0)
  • 2020-12-31 01:16

    You can use the join method. Refer to the documentation here

    0 讨论(0)
  • 2020-12-31 01:17

    You can add a shutdown hook for the "Its Over" message. This way it will be produced when the program finishes and you don't have to wait for each thread.

    0 讨论(0)
  • 2020-12-31 01:19

    Try This example:

    public class JoinTest extends Thread { 
    
        public static void main(String[] args) 
        {
            JoinTest t = new JoinTest();
            t.start();
    
            try {
    
                t.join();
                int i = 0;
                while(i<5)
                {
                    System.out.println("parent thread is running......" +i++);
                }
    
            } catch (Exception e) {
                // TODO: handle exception
            }
    
    
        }
    
    
        public void run()
        {
    
            try {
    
                int i =0;
                while(i<5)
                {
                    System.out.println("child thread running ........." +i++);
                }
    
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-31 01:27

    You could wait() in your main thread and have all threads issue a notifyAll() when they're done. Then each time your main thread gets woken up that way, it can check if there's at least one thread that's still alive in which case you wait() some more.

    0 讨论(0)
提交回复
热议问题