Search code examples
javamultithreadingworker

Java Worker Thread to Wait


I have a thread working in the background and but it doesn't always has work to do. I want it to wait for data to be passed by the main thread and then continue working.

At first I thought that's what wait() and notify() were for but it seems to work the other way around.

How do I do that?


Solution

  • See my comment.

    Sounds like you want a BlockingQueue -- this is a very common requirement for producer-consumer problems. Try not to reinvent the wheel ;-)

    There exist multiple BlockingQueue implementations, e.g. a bounded ArrayBlockingQueue, an unbounded LinkedBlockingQueue, a hand-off SynchronousQueue, even a PriorityBlockingQueue. All BlockingDeques and TransferQueues are also BlockingQueues ;-)