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

查看:20
本文介绍了如何中断 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.

有没有办法中断scanner的阻塞,让它返回?

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天全站免登陆