Question

I have two threads. Thread A is pulling some elements from queue and thread B is adding some elements to the queue.

I want thread A to go to sleep when the queue is empty.

When thread B adds some element to the queue it should make sure that thread A is working. How can this be done in Java?

Was it helpful?

Solution

Use a BlockingQueue, which is:

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

Seriously, don't try to reinvent the wheel here.




(If you must use wait/notify, read this tutorial. But spare yourself the pain, please!)

OTHER TIPS

Here are some details:

import java.concurrent.Executors;
import java.concurrent.ExecutorService;
...
ExecutorService executor = Executors.newFixedThreadPool(someNumberOfThreads);
...
executor.execute(someObjectThatImplementsRunnable);
...
executor.shutdownNow();

That's all there is to it with Java's newer threading capabilities. Executor is a thread pool with someNumberOfThreads in it. It is fed by a blocking queue. All the threads sleep unless there is work to do. When you push a Runnable object into the queue using the execute() method, the Runnable object sits in the queue until there is a thread available to process it. Then, it's run() method is called. Finally, the shutdownNow() method signals all threads in the pool to shutdown.

It's much simpler now than it used to be.

(There are lots of variations on this, such as pools with minimum and maximum numbers of threads, or queues which have maximum sizes before threads calling execute() will block.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top