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
Have a look at various solutions.
join()
API has been introduced in early versions of Java. Some good alternatives are available with this concurrent package since the JDK 1.5 release.ExecutorService#invokeAll()
Refer to this related SE question for code example:
How to use invokeAll() to let all thread pool do their task?
CountDownLatch
Refer to this question for usage of
CountDownLatch
How to wait for a thread that spawns it's own thread?
ForkJoinPool or newWorkStealingPool() in Executors
Iterate through all Future objects created after submitting to
ExecutorService
Store the Thread-objects into some collection (like a List or a Set), then loop through the collection once the threads are started and call join() on the Threads.
try this, will work.
An executor service can be used to manage multiple threads including status and completion. See http://programmingexamples.wikidot.com/executorservice
I had a similar problem and ended up using Java 8 parallelStream.
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.
The approach I take is to use an ExecutorService to manage pools of threads.