Xen*_*nce 6 java java.util.scanner
我正在尝试编写一个循环,直到我在运行应用程序的控制台中键入特定文本.就像是:
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
}}
Run Code Online (Sandbox Code Playgroud)
而且我希望它在每次通过时写一行,所以我不希望它在一段时间内停止并等待下一个输入.我需要使用多个线程吗?
我需要使用多个线程吗?
是.
由于使用Scanneron System.in表示您正在阻止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.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14643 次 |
| 最近记录: |