CC.
CC.

Reputation: 2928

java threads : producer - consumer

I have some developpements to do and I try to see if there is a desing pattern to use. The problem is simple:

I have a main thread that launches many treads. The main thread must wait for each thread to finish and then doing something else. The existing code it's a bit ugly. I have a while loop that check a thread group to see if is something running:

//launch threads
.....
//wait for threads to finish
while (ThreadRepository.getInstance().isActiveThreadGroup(myGroupId)) {
    Thread.sleep(5000);
}

//doing something else

So, as you see, the while loop keeps running until no threads running.

I was thinking at the pattern producer-consumer and I would like to do something like that:

Using some BlockingQueue for instance, and each thread put (or take) something in it. Instead of having the while and sleep I would like to have something like myQueue.take() but something to wait for the queue to be empty. When empty, it means no threads running.

I try to search on the Internet but I did not found something that matches my problem.

Does anyone know the most efficient to solve my problem ?

Upvotes: 1

Views: 277

Answers (2)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

You can use BlockingQueue as follows:

  • each child thread puts a message in the queue when finished

  • the main thread takes messages from the queue and counts them. When the number of messages equals the number of threads, all threads has finished.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692281

There are two easy ways to have one thread wait for N threads to finish:

  1. Make the main thread call join() on all the other threads. join() returns when a thread finishes, or has already finished
  2. Create a CountDownLatch initialized to N, pass this latch to all the threads, make each thread call countDown() on the latch when it has finished, and make the main thread call await() on the latch. This second technique is a bit harder than the first one, but is also more flexible and reusable, and allows being awaken after some delay, even if the N threads have not finished yet.

Upvotes: 2

Related Questions