views:

69

answers:

3

Im trying to do a simple game where I continually need input from players. This needs to happen during a certain time period only. Everything that is sent after that will be discarded. After the time period a new game starts. So:

  1. Start game
  2. Wait for input from all players during 10 seconds
  3. > 10 secs no more input
  4. Calculate the winner and do some stuff
  5. Goto 1.

I was thinking using a timer and timertask to keep track of time and maybe use a boolean variable that changes from "open" to "closed" after 10 seconds? Please give me some advise on this.

A: 

You're right, with a timer you can change that value:

 Timer timer = new Timer();
 timer.schedule( new TimerTask(){
       public void run() {
            synchronized( lock ) { 
                isOpen = false;
            }
        }
   }, 10000 );

And that's it. The method inside run will be executed 10 seconds after you call schedule

EDIT

Sample:

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
import static java.lang.System.out;

public class Test {
    public static void main( String [] args ) {
        Timer timer = new Timer();
        timer.schedule( new TimerTask(){
            public void run() {
                out.println(new Date()+" No more bets, thank you!");
            }
        }, 10000 );
        out.println(new Date() + " Place your bets, place your bets!!");
    }
}
OscarRyz
A: 

Yes, you'll need a timer, and some kind of an "open/closed" flag will be the way to go.

Be sure to make your flag "volatile" so all the threads reading your input see the change at once.

Come to think of it, you might even think of having the timer task hit each of the reader threads with an interrupt, so they all get told at once, rather than whenever they pop up to check.

CPerkins
+1  A: 

Rather than use a Timer and TimerTask, I'd update your thinking to the more current way of using Executors. With a ScheduledExecutor you could schedule a Runnable like:

// class member or perhaps method var
private boolean acceptInput = true;

// elsewhere in code
ScheduledExecutor executor = new ScheduledExecutor(1);
startGame();
mainLoop();
executor.schedule(flipInput, 10, TimeUnit.SECONDS);

// inner class
private class FlipInput implements Runnable {
    public void run() {
        acceptInput = !acceptInput;
        calculateWinner();
        doSomeStuff();
        startGame();
        executor.schedule(flipInput, 10, TimeUnit.SECONDS);
        mainLoop();
    }
}
justkt