1

Seen many other similar questions like this on this website and i would say none of them have been fully answered before critisim is made about this post.

Its a simple issue i have to use a timer for 30 seconds and retrive user input (string) like below..

while (timer is still less than 30 seconds)
      allow user to enter input (using either scanner, buffered reader)

I know threading will be required but not sure how to impleneted this atal, and seems to be alot more complicated than i first set out to be.

thanks

Lemex
  • 3,772
  • 14
  • 53
  • 87

1 Answers1

0

Try doing the following (no threads attached ;)) :

long startTime = System.currentTimeMillis();
long timeElapsed;
do {
    // Get user input
    .
    .


    // Process input
    .
    .

    // Check time elapsed
    timeElapsed = (System.currentTimeMillis() - startTime) / 1000;

} while (timeElapsed < 30);

Bear in mind that I assume that getting user input is blocking. (otherwise the while loop will choke the cpu for which I advice to put a sleep statement of say 100ms)

giorashc
  • 13,691
  • 3
  • 35
  • 71
  • This is a good suggestion but does this not cause it just to halt on user input , waiting on the user input for any amount of time this is why a thought tdreading would have to be used... – Lemex Apr 01 '12 at 14:18
  • 1
    Now I understand where you getting at. Look here : http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread. The first answer will solve your problem. In general you execute a task (in your case its geting user input) with a pre-defined timeout. – giorashc Apr 01 '12 at 14:30