简体   繁体   English

Java-带计时器的用户输入线程

[英]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.. 这是一个简单的问题,我必须使用计时器30秒并检索如下的用户输入(字符串)。

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. 我知道将需要线程,但不确定如何实现此atal,并且似乎比我最初提出的要复杂得多。

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) (否则,while循环将阻塞我建议为其输入100ms睡眠状态的CPU)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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