在用户输入上设置超时 [英] Set timeout on user input

查看:111
本文介绍了在用户输入上设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to set a timeout on user input in a java console application with the following code

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秒后,如果用户未输入任何内容,则会显示超时消息.但是,每当用户尝试输入内容时,程序就会卡住,并且不会返回输入内容

After 10 seconds, the timeout message is displayed when the user doesn't input anything. But whenever user tries to input something, the program gets stuck and doesn't return the input

推荐答案

更正较小的编译问题并输出input的值,代码在成功输入时就可以很好地工作:

Correcting minor compilation issues and outputting the value of input the code works perfectly fine on successful 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();
        }

    }
}

打印

输入:wfqwefwfqer

input: wfqwefwfqer

wfqwefwfqer

wfqwefwfqer

以退出代码0结束的过程

Process finished with exit code 0

您的代码,但是,在超时上存在错误:shutdownNow并没有真正杀死输入线程,并且应用程序继续运行以等待输入,并且仅在接收到一些输入并终止线程后才退出一般.但这不在您的问题范围内.

Your code, however, has a bug on timeout: shutdownNow does not really kill the input thread and the application keeps running waiting for input and only quitting after receiving some input and terminating the thread normally. But this was not in scope of your question.

这篇关于在用户输入上设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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