Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How can a thread wait on multiple objects?

Tags:

A thread can use Object.wait() to block until another thread calls notify() or notifyAll() on that object.

But what if a thread wants to wait until one of multiple objects is signaled? For example, my thread must wait until either a) bytes become available to read from an InputStream or b) an item is added to an ArrayList.

How can the thread wait for either of these events to occur?

EDIT

This question deals with waiting for multiple threads to complete -- my case involves a thread waiting for one of many objects to be singnaled.

like image 517
Tony the Pony Avatar asked Jun 07 '11 12:06

Tony the Pony


1 Answers

You are in for a world of pain. Use a higher level abstraction, such as a blocking message queue, from which the thread can consume messages such as 'more bytes available' or 'item added'.

like image 167
artbristol Avatar answered Dec 09 '22 18:12

artbristol