How to stop Java Scanner from accepting input

大兔子大兔子 提交于 2019-12-06 11:49:21

A Java Scanner is using blocking operations. It is not possible to stop it. Not even using Thread.interrupt();

You can however read using a BufferedLineReader and be able to stop the thread. It's not a neat solution, as it involves pausing for short moments (otherwise it would use 100 % CPU), but it does work.

public static class ConsoleInputReadTask {
    private final AtomicBoolean stop = new AtomicBoolean();

    public void stop() {
        stop.set(true);
    }

    public String requestInput() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("ConsoleInputReadTask run() called.");
        String input;
        do {
            System.out.println("Please type something: ");
            try {
                // wait until we have data to complete a readLine()
                while (!br.ready() && !stop.get()) {
                    Thread.sleep(200);
                }
                input = br.readLine();
            } catch (InterruptedException e) {
                System.out.println("ConsoleInputReadTask() cancelled");
                return null;
            }
        } while ("".equals(input));
        System.out.println("Thank You for providing input!");
        return input;
    }
}

public static void main(String[] args) {
    final Thread scannerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String string = new ConsoleInputReadTask().requestInput();
                System.out.println("Input: " + string);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
    scannerThread.start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            scannerThread.interrupt();
        }
    }).start();
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!