问题
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