且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在用户输入上设置超时

更新时间:2023-12-04 18:23:59

更正较小的编译问题并输出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.