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?
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.
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.
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.
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.
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()
.
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With