如何在扫描仪输入之前运行一段时间?

我正在尝试编写一个循环,直到我在运行应用程序的控制台中键入特定文本。 就像是:

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 }} 

我希望它在每次通过时写一行,所以我不希望它在一段时间内停止并等待下一个输入。 我需要使用多个线程吗?

我需要使用多个线程吗?

是。

由于在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. } } 

是的,你需要两个线程。 第一个可以做这样的事情:

 //accessible from both threads CountDownLatch latch = new CountDownLatch(1); //... while ( true ) { System.out.println("Waiting for input..."); if ( latch.await(2, TimeUnit.SECONDS) ) { break; } } 

和另外一个:

 Scanner scanner = new Scanner(System.in); while ( !"STOP".equalsIgnoreCase(scanner.nextLine()) ) { } scanner.close(); latch.countDown();