views:

122

answers:

6

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?

+1  A: 

You may add Thread.sleep() with appropriate time to minimize useless loop iterations.

Another solution is using synchronization. While threads are not required to do anything, they enter into a sleeping state on a monitor using the wait() method, and then when the turn comes, required thread is woken up by the notify() method.

Malcolm
+4  A: 

While yes, you need a loop (while is 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:

loop {
    event = WaitForEvent();
    RespondToEvent(event);
} until done;

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 an ArrayBlockingQueue is 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:

public abstract class EventHandlingThread<Event> extends Thread {
    private ArrayBlockingQueue<Event> queue = new ArrayBlockingQueue<Event>();
    private boolean done;

    protected abstract void respondToEvent(Event event);
    public final void postEvent(Event event) throws InterruptedException {
        queue.put(event);
    }
    protected final void done() {
        done = true;
    }
    public final void run() {
        try {
            while (!done) {
                respondToEvent(queue.take());
            }
        } catch (InterruptedException e) {
            // Maybe log this, maybe not...
        } catch (RuntimeException e) {
            // Probably should log 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 call done() 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…

Donal Fellows
but then what would be WaitForEvent() be? this would just be shifting the problem from run() to WaitForEvent()
TP
@TP: Edited my answer to show how via an outline of a class. Subclass it to add your event handler(s) and you're done.
Donal Fellows
An interesting way to solve it by using blocking calls on a buffer. Thanks
TP
A: 

You should test for a condition in the while loop:

while (!gameOver) 
{
   do_intersting_stuff();
}

Heavy CPU load is typical for busy wait. Is your loop actually just checking a flag over and over, like

while (!gameOver) 
{
   if (actionNeeded)
   {
      do_something();
   }
}

you might change to another notification system to sleep and wake up, as this just burns CPU time for nothing.

Eiko
+2  A: 

I would look into Locks and Conditions. This way you can write code that waits for a certain condition to happen. This won't take a lot of CPU power and is even much more efficient and better performing than sleeping .

Marc
+1  A: 

Actor model seems suitable for this scenario. Each person sitting on the table and the table itself can be modelled as actors and the event of passing the tokens and starting and stopping of the game can be modelled as messages to be passed between the actors.

As a bonus, by modelling the scenario as actors you get rid of explicit manipulation of threads, synchronization and locking.

On JVM I will prefer using Scala for modelling actors. For Java you can use libraries like Kilim. See this post for a comparison of Actor model related libraries in Java.

abhin4v
A: 

One Way is to use while loop but keep a check i.e

while(true){
if(condition!=true){
Thread.sleep(time);
}else{
break;
}
}

This way if your condition says game is not over it will keep person thread at sleep and memory consumption will be very low.

Shashank T