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

后端 未结 9 894
无人及你
无人及你 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:32

    You could share a CyclicBarrier object among your RaceCars and your main thread, and have the RaceCar threads invoke await() as soon as they are done with their task. Construct the barrier with the number of RaceCar threads plus one (for the main thread). The main thread will proceed when all RaceCars have finished. See http://java.sun.com/javase/6/docs/api/java/util/concurrent/CyclicBarrier.html

    In detail, construct a CyclicBarrier in the main thread, and add a barrier.await() call in your RaceCar class just before the run() method exits, also add a barrier.await() call before the System.out.println() call in your main thread.

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

    You could make the last line be in a "monitoring" thread. It would check every so often that it is the only running thread and some completion state == true and then could fire if it was. Then it could do other things than just println

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

    Simplest way

    while (Thread.activeCount() > 1) {
    }
    

    I know it block main thread... but it works perfectly!

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