Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, how to wait on multiple `Conditions` until any one of them is signaled

Suppose an elevator simulation program, visitors about to take a ride are to wait until any one of the elevator doors opens. i.e. I want to wait on multiple Conditions until any one of them is signaled.

Actually, it doesn't have to be Conditions, other approaches that can fulfill my need is welcome.

How can this be done in Java?

like image 341
Haozhun Avatar asked Feb 25 '11 13:02

Haozhun


People also ask

Can a thread wait on multiple locks?

When two locks are held simultaneously, a wait call only releases one of them. The other will be held until some other thread requests a lock on the awaited object. If no unrelated code tries to lock on that object, then all other threads will be locked out, resulting in a deadlock.

How do you make a thread wait for some time?

In between, we have also put the main thread to sleep by using TimeUnit. sleep() method. So the main thread can wait for some time and in the meantime, T1 will resume and complete its execution.

How do you wait a method in Java?

wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). The current thread must own this object's monitor.

Which of the following method block a thread until a condition satisfy?

Blocking methods in java are the particular set of methods that block the thread until its operation is complete. So, they will have to block the current thread until the condition that fulfills their task is satisfied. Since, in nature, these methods are blocking so-called blocking methods.


3 Answers

You might find CountDownLatch does the job you need. You would instantiate the latch with a count of 1:

CountDownLatch latch = new CountDownLatch(1);

and then share it between your threads. All the threads that wait for the doors to open will do latch.await(). This method will not return until another thread calls latch.countDown().

like image 85
Rich Avatar answered Oct 16 '22 09:10

Rich


You might want to check out Observer and Observable. You will still have to handle treading issues but with Observer you at least have an easy way for the simulator to know when a door opens (triggers an event)

like image 24
Andrew White Avatar answered Oct 16 '22 08:10

Andrew White


Rather than a set of conditions, I'd use a BlockingQueue<Door>, (Door is an enum of the doors in the lift) where threads which want to use a door call take() on the queue, and threads which are opening a door call put(Door.ONE). and then uses drainTo to remove any other open doors (presumably there's another mechanism to tell the door opening threads that the lift has left and that they can't open any more doors).

like image 31
tgdavies Avatar answered Oct 16 '22 08:10

tgdavies