如何让扫描仪运行一段时间才能获得输入?
我正在尝试编写一个循环,该循环运行直到我在运行应用程序的控制台中键入特定文本。比如:
while (true) {
try {
System.out.println("Waiting for input...");
Thread.currentThread();
Thread.sleep(2000);
if (input_is_equal_to_STOP){ // if user type STOP in terminal
break;
}
} catch (InterruptedException ie) {
// If this thread was intrrupted by nother thread
}}
我希望它每次通过时都写一行,所以我不希望它在一段时间内停止并等待下一个输入。我需要为此使用多个线程吗?
I'm trying to write a loop which runs until I type a specific text in console where the application is running. Something like:
while (true) {
try {
System.out.println("Waiting for input...");
Thread.currentThread();
Thread.sleep(2000);
if (input_is_equal_to_STOP){ // if user type STOP in terminal
break;
}
} catch (InterruptedException ie) {
// If this thread was intrrupted by nother thread
}}
And I want it to write a line each time it pass through so I do not want it to stop within the while and wait for next input. Do I need to use multiple threads for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。
由于在
System.in
上使用Scanner
意味着您正在执行阻塞 IO,因此需要一个线程专门用于读取用户输入的任务。这是一个帮助您入门的基本示例(不过,我鼓励您查看 java.util.concurrent 包来执行这些类型的操作。):
Yes.
Since using a
Scanner
onSystem.in
implies that you're doing blocking IO, one thread will need to be dedicated for the task of reading user input.Here's a basic example to get you started (I encourage you to look into the
java.util.concurrent
package for doing these type of things though.):是的,为此您需要两个线程。第一个可以做这样的事情:
另一个:
Yes, you would need two threads for this. The first could do something like this:
And the other: