I am trying to program a game in which I have a Table class and each person sitting at the table is a separate thread. The game involves the people passing tokens around and then stopping when the party chime sounds.
how do i program the run() method so that once I start the person threads, they do not die and are alive until the end of the game
One solution that I tried was having a while (true) {} loop in the run() method but that increases my CPU utilization to around 60-70 percent. Is there a better method?
While yes, you need a loop (
whileis only one way, but it is simplest) you also need to put something inside the loop that waits for things to happen and responds to them. You’re aiming to have something like this pseudocode:OK, that’s the view from 40,000 feet (where everything looks like ants!) but it’s still the core of what you want. Oh, and you also need something to fire off the first event that starts the game, obviously.
So, the key then becomes the definition of
WaitForEvent(). The classic there is to use a queue to hold the events, and to make blocking reads from the queue so that things wait until something else puts an event in the queue. This is really a Concurrency-101 data-structure, but anArrayBlockingQueueis already defined correctly and so is what I’d use in my first implementation. You’ll probably want to hide its use inside a subclass of Thread, perhaps like this:Subclass that for each of your tasks and you should be able to get going nicely. The
postEvent()method is called by other threads to send messages in, and you calldone()on yourself when you’ve decided enough is enough. You should also make sure that you’ve always got some event that can be sent in which terminates things so that you can quit the game…