In java, how to wait for a few "Conditions" until one of them is signaled

Assume that the elevator simulation program, visitors about to ride must wait until a single elevator door opens. those. I want to wait for a few Conditions until one of them is signaled.

In fact, this should not be Conditions , other approaches that can satisfy my needs are welcome.

How can this be done in Java?

+7
source share
4 answers

You might find CountDownLatch the job you need. You must create an instance of the latch with a score of 1:

 CountDownLatch latch = new CountDownLatch(1); 

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

+6
source

You might want to check out Observer and Observable . You still have to deal with tread problems, but with Observer, you at least have a simple way for the simulator to know when the door opens (triggers an event)

+5
source

Instead of a set of conditions, I would use BlockingQueue<Door> , ( Door is an enumeration of doors in an elevator), where are the threads that want to use the take() door call in the queue, and the threads that open the put(Door.ONE) . and then uses drainTo to remove any other open doors (presumably there is another mechanism to say that doors open the threads left by the elevator and that they cannot open more doors).

+1
source

Generally speaking, Lock protects a shared state, and Condition used to wait for a specific condition in that state.

But in your task, you actually have two sets of orthogonal states - elevator states and floor states. This means that if you want to use the Lock / Condition primitives to work with this task, you need to create separate locks and conditions for these states.

That is, when the elevator rises to the floor, it acquires its own lock and floor lock, and then signals the condition associated with the floor, so that visitors waiting on the floor wake up. Also pay attention to the lock order to avoid locks in this scheme.

+1
source

All Articles