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

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

提交回复
热议问题