Set timeout on user input

℡╲_俬逩灬. 提交于 2019-12-11 02:18:40

问题


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();
}

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


回答1:


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();
        }

    }
}

Prints

input: wfqwefwfqer

wfqwefwfqer

Process finished with exit code 0

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.



来源:https://stackoverflow.com/questions/49592555/set-timeout-on-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!