You can use a java.util.Timer
object, which can be reset in the enter
method. The timer task will run in its own thread and do the picking for you if it is not canceled before hand.
Note that the enter
method will be running on one of the many Guest
threads. This means that it should probably synchronized. The easiest way to do this is is to add the synchronized
keyword to the method declaration in Java: public synchronized void enter(Guest g)
. This will ensure that only one guest can enter at a time. You can put the timer cancel/restart code in here.
The way java.util.Timer
works it through the abstract java.util.TimerTask
class. This is a type of Runnable
that also has a method to cancel the task. My recommendation is to schedule a task that will pick guests after a 5000ms interval whenever a guest enters. If a task from the previous guest is running, cancel it first.
The enter
method should acquire the guest's lock (using a synchronized block) and have the guest wait. The picking should call the notify()
method on the guests you select. This will allow them to continue executing.
When you remove selected guests from your queue, be aware of the fact that Java collections are not thread-safe by default. You will have to use an external lock to ensure that no-one else is modifying your list when you add and remove guests. The Collections.synchronizedList(List)
method provides a handy way to do this.
Here is a list of links that discuss the topics I have mentioned:
- http://docs.oracle.com/javase/tutorial/essential/concurrency/ (excellent tutorial for beginners)
- http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
- http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html
- http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29