问题描述
我正在尝试编写一个循环,直到我在运行应用程序的控制台中键入特定文本。类似于:
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?
推荐答案
是。
自在 System.in
上使用 Scanner
意味着你正在阻止IO,一个线程需要专门用于阅读用户输入的任务。
Since using a Scanner
on System.in
implies that you're doing blocking IO, one thread will need to be dedicated for the task of reading user input.
这是一个让你入门的基本例子(我鼓励你去研究 java.util.concurrent
用于执行这些类型的东西的包。):
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.):
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.
}
}
这篇关于如何在扫描仪输入之前运行一段时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!