Java: How can a thread wait on multiple objects?

Tony the Pony picture Tony the Pony · Jun 7, 2011 · Viewed 15.8k times · Source

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.

Answer

artbristol picture artbristol · Jun 7, 2011

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'.