JAVA: How do I accept input during a certain period of time only
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:
- Start game
- Wait for input from all players during 10 seconds
10 secs no more input
- Calculate the winner and do some stuff
- 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 gi开发者_Go百科ve me some advise on this.
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();
}
}
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!!");
}
}
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.
精彩评论