设置用户输入超时

Set timeout on user input

我正在尝试使用以下代码在 java 控制台应用程序中设置用户输入超时

ExecutorService executor = Executors.newSingleThreadExecutor();
Callable task =() ->  {
    System.out.print("input: ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    return br.readLine();
};
Future future = executor.submit(task);
String input = null;
try {
     input = (String)future.get(10, TimeUnit.SECONDS);

} catch (TimeoutException e) {
    future.cancel(true);
    System.out.println("Sorry you run out of time!"));
} catch (InterruptedException | ExecutionException e) {
     e.getMessage();
} finally {
   executor.shutdownNow();
}

10 秒后,当用户未输入任何内容时,将显示超时消息。但是每当用户尝试输入某些内容时,程序就会卡住并且不会 return 输入

更正小的编译问题并输出 input 的值代码在成功输入时运行良好:

public class Foo {

    public static void main(String[] argv) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Callable task =() ->  {
            System.out.print("input: ");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            return br.readLine();
        };
        Future future = executor.submit(task);
        try {
            String input = (String)future.get(10, TimeUnit.SECONDS);
            System.out.println(input);
        } catch (TimeoutException e) {
            future.cancel(true);
            System.out.println("Sorry you run out of time!");
        } catch (InterruptedException | ExecutionException e) {
            e.getMessage();
        } finally {
            executor.shutdownNow();
        }

    }
}

版画

input: wfqwefwfqer

wfqwefwfqer

Process finished with exit code 0

但是,您的代码 存在超时错误 shutdownNow 并未真正终止输入线程,应用程序一直 运行 等待输入并且只有在收到一些输入并正常终止线程后才退出。但这不在你的提问范围内。