java – 如何在扫描仪输入之前运行一段时间?
作者:互联网
我正在尝试编写一个循环,直到我在运行应用程序的控制台中键入特定文本.就像是:
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
}}
而且我希望它在每次通过时写一行,所以我不希望它在一段时间内停止并等待下一个输入.我需要使用多个线程吗?
解决方法:
Do I need to use multiple threads for this?
是.
由于在System.in上使用Scanner意味着您正在阻止IO,因此需要专门用于读取用户输入的任务.
这是一个帮助您入门的基本示例(我鼓励您查看java.util.concurrent包以执行这些类型的操作.):
import java.util.Scanner;
class Test implements Runnable {
volatile boolean keepRunning = true;
public void run() {
System.out.println("Starting to loop.");
while (keepRunning) {
System.out.println("Running loop...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
System.out.println("Done looping.");
}
public static void main(String[] args) {
Test test = new Test();
Thread t = new Thread(test);
t.start();
Scanner s = new Scanner(System.in);
while (!s.next().equals("stop"));
test.keepRunning = false;
t.interrupt(); // cancel current sleep.
}
}
标签:java-util-scanner,java 来源: https://codeday.me/bug/20191008/1870670.html