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

喜夏-厌秋 提交于 2019-12-01 04:48:50

Do I need to use multiple threads for this?

Yes.

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.

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

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!