Reputation: 11293
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?
Upvotes: 1
Views: 877
Reputation: 533442
I would suggest you use an ExecutorService. I combines a queue with a Thread pool.
You submit tasks to it which are performed in the background as it can and you can obtain the result if you want.
ExecutorService service = Executors.newWhateverPool();
service.submit(new Runnable() { your task here });
Upvotes: 6
Reputation: 29636
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 BlockingDeque
s and TransferQueue
s are also BlockingQueue
s ;-)
Upvotes: 6