user2891462
user2891462

Reputation: 3333

Interrupt sleep in a single thread

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

Answers (3)

M A
M A

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

drew moore
drew moore

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

vandale
vandale

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

Related Questions