wait until all threads finish their work in java

后端 未结 16 1885
情深已故
情深已故 2020-11-22 14:10

I\'m writing an application that has 5 threads that get some information from web simultaneously and fill 5 different fields in a buffer class.
I need to validate buffer

相关标签:
16条回答
  • 2020-11-22 15:02

    Apart from Thread.join() suggested by others, java 5 introduced the executor framework. There you don't work with Thread objects. Instead, you submit your Callable or Runnable objects to an executor. There's a special executor that is meant to execute multiple tasks and return their results out of order. That's the ExecutorCompletionService:

    ExecutorCompletionService executor;
    for (..) {
        executor.submit(Executors.callable(yourRunnable));
    }
    

    Then you can repeatedly call take() until there are no more Future<?> objects to return, which means all of them are completed.


    Another thing that may be relevant, depending on your scenario is CyclicBarrier.

    A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

    0 讨论(0)
  • 2020-11-22 15:04

    I had a similar problem and ended up using Java 8 parallelStream.

    requestList.parallelStream().forEach(req -> makeRequest(req));
    

    It's super simple and readable. Behind the scenes it is using default JVM’s fork join pool which means that it will wait for all the threads to finish before continuing. For my case it was a neat solution, because it was the only parallelStream in my application. If you have more than one parallelStream running simultaneously, please read the link below.

    More information about parallel streams here.

    0 讨论(0)
  • 2020-11-22 15:05

    I created a small helper method to wait for a few Threads to finish:

    public static void waitForThreadsToFinish(Thread... threads) {
            try {
                for (Thread thread : threads) {
                    thread.join();
                }
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    0 讨论(0)
  • 2020-11-22 15:05

    Use this in your main thread: while(!executor.isTerminated()); Put this line of code after starting all the threads from executor service. This will only start the main thread after all the threads started by executors are finished. Make sure to call executor.shutdown(); before the above loop.

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