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 data and store it in a database when all threads finished their job.
How can I do this (get alerted when all threads finished their work) ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You do
After this for loop, you can be sure all threads have finished their jobs.
Although not relevant to OP's problem, if you are interested in synchronization (more precisely, a rendez-vous) with exactly one thread, you may use an Exchanger
In my case, I needed to pause the parent thread until the child thread did something, e.g. completed its initialization. A CountDownLatch also works well.
You can
join
to the threads. The join blocks until the thread completes.Note that
join
throws anInterruptedException
. You'll have to decide what to do if that happens (e.g. try to cancel the other threads to prevent unnecessary work being done).Apart from
Thread.join()
suggested by others, java 5 introduced the executor framework. There you don't work withThread
objects. Instead, you submit yourCallable
orRunnable
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 theExecutorCompletionService
:Then you can repeatedly call
take()
until there are no moreFuture<?>
objects to return, which means all of them are completed.Another thing that may be relevant, depending on your scenario is
CyclicBarrier
.Another possibility is the
CountDownLatch
object, which is useful for simple situations : since you know in advance the number of threads, you initialize it with the relevant count, and pass the reference of the object to each thread.Upon completion of its task, each thread calls
CountDownLatch.countDown()
which decrements the internal counter. The main thread, after starting all others, should do theCountDownLatch.await()
blocking call. It will be released as soon as the internal counter has reached 0.Pay attention that with this object, an
InterruptedException
can be thrown as well.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.