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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5463968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:14:05  来源:igfitidea点击:

How to make a while to run until scanner get input?

javajava.util.scanner

提问by Xenovoyance

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?

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

采纳答案by aioobe

Do I need to use multiple threads for this?

我需要为此使用多个线程吗?

Yes.

是的。

Since using a Scanneron System.inimplies that you're doing blocking IO, one thread will need to be dedicated for the task of reading user input.

由于使用ScanneronSystem.in意味着您正在执行阻塞 IO,因此需要一个线程专用于读取用户输入的任务。

Here's a basic example to get you started (I encourage you to look into the java.util.concurrentpackage for doing these type of things though.):

这是一个让您入门的基本示例(不过,我鼓励您查看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.
    }
}

回答by Mark Peters

Yes, you would need two threads for this. The first could do something like this:

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

//accessible from both threads
CountDownLatch latch = new CountDownLatch(1);

//...
while ( true ) {
    System.out.println("Waiting for input...");
    if ( latch.await(2, TimeUnit.SECONDS) ) {
       break;
    }
}

And the other:

和另外一个:

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