wait until all threads finish their work in java

后端 未结 16 2233
情深已故
情深已故 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.

提交回复
热议问题