简体   繁体   中英

Java - User input threadin with timer

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM