Reputation: 3333
I would like to implement in Java a stop point in the code so that nothing is done in 20 seconds unless the user presses Enter. For the moment I am just using:
sleep(20000);
I know a thread can be "awaken" by another thread using wait()
and notify()
, but I would like to know if there is something that does not require throwing a new thread. Ideally, I would like to be able to add a timeout to the read operations on a InputStream from the keyboard, so that I could do something like:
try {
//Here is where the waiting happens
myStream.read();
} catch (TimeoutException e) { }
//... Continue normally
Upvotes: 0
Views: 135
Reputation: 72844
A blocking read with timeout interruption cannot be accomplished using one thread since a read from the input stream blocks indefinitely. There is a way to execute a computation with a timeout using a Future, but this involves concurrent programming in the first place.
Upvotes: 1
Reputation: 32670
The comments are correct, but to suggest a (somewhat hacky) workaround:
BufferedReader myStream = new BufferedReader(new InputStreamReader(System.in));
long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() < (startTime + 20000)) {
if (myStream.ready()) {
//do something when enter is pressed
break;
}
}
Upvotes: 1
Reputation: 3650
You could instead of sleeping for 20s instead sleep for 1 second intervals and poll to see if the user has entered anything:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 20; i++) {
try {
sleep(1000);
if (in.ready()) {
break;
} else {
System.out.println(i+" seeconds have passed");
}
} catch (InterruptedException | IOException ex) {
}
}
Upvotes: 2