开发者

Have threads run indefinitely in a java application

开发者 https://www.devze.com 2023-01-02 16:51 出处:网络
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 par

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 t开发者_如何学Cried 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 (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…


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 .


To make a thread run for an infinite time:


final Object obj = new Object(); 
try {
    Thread th = new Thread(new Runnable() {
        public void run() {
            synchronized(obj) {
                try {                        
                    System.out.println("Waiting");
                    obj.wait();
                    System.out.println("Done waiting");
                }catch(Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    });                     
    th.start();
    System.out.println("Waiting to join.");
    // Dont notify; but wait for joining. This will ensure that main thread is running always.
    th.join();
    System.out.println("End of the Program");            
} catch(Exception ex) {
    ex.printStackTrace();
}


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消