如何中断java.util.Scanner nextLine调用 [英] How to interrupt java.util.Scanner nextLine call

查看:394
本文介绍了如何中断java.util.Scanner nextLine调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用多线程环境是一个线程不断地监听用户输入通过重复调用 scanner.nextLine()
要结束应用程序,此runloop由另一个线程停止,但监听线程将不会停止,直到最后一个用户输入(由于 nextLine())。

I am using a multi threaded environment were one Thread is constantly listening for user input by repeatedly calling scanner.nextLine(). To end the application, this runloop is stopped by another thread, but the listening thread won't stop until a last user input was made (due to the blocking nature of nextLine()).

关闭流似乎不是一个选项,因为我从System.in读取,它返回一个 InputStream

Closing the stream seems not to be an option since I am reading from System.in, which returns an InputStream that is not closable.

有没有办法中断扫描程序的阻塞,以便它会返回?

Is there a way to interrupt the blocking of scanner, so that it will return?

感谢

推荐答案

文章介绍了一种在阅读时避免阻止的方法。它提供了代码片段,您可以在注释中修改。

This article describes an approach to avoiding blocking when reading. It gives the code snippet, which you could amend as I indicate in a comment.

import java.io.*;
import java.util.concurrent.Callable;

public class ConsoleInputReadTask implements Callable<String> {
  public String call() 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()  /*  ADD SHUTDOWN CHECK HERE */) {
          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;
  }
}

您可以直接使用此代码,新的可关闭InputStream类,包装本文中描述的逻辑。

You could either use this code directly, or write a new closable InputStream class, wrapping up the logic described in this article.

这篇关于如何中断java.util.Scanner nextLine调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆