问题
It seems to me that once a thread starts reading input via System.console().readLine()
or System.in.read()
, there is absolutely no way in the universe to functionally interrupt the read, except for System.exit()
or providing input.
interrupt()
ing the reading thread does nothing. Even stop()
ing it does nothing. close()
ing System.in
during System.in.read()
does nothing until after the read completes by providing input. The read methods don't take any timeout parameters nor time out on their own.
Is there just no way at all to "unlock" a thread waiting for console input that will never come?
回答1:
I created a variation based on this article
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;
public class ConsoleInputReadTask implements Callable<String> {
private boolean cont = true;
public void stop() {
cont = false;
}
public String call() throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("ConsoleInputReadTask run() called.");
String input;
try {
// wait until we have data to complete a readLine()
while (!br.ready()) {
Thread.sleep(200);
if (!cont) {
System.out.println("ConsoleInputReadTask() stopped");
return null;
}
}
input = br.readLine();
} catch (InterruptedException e) {
System.out.println("ConsoleInputReadTask() cancelled");
return null;
}
return input;
}
}
Part of main program
private ConsoleInputReadTask consoleInputReadTask;
public String readLine() throws InterruptedException {
ExecutorService ex = Executors.newSingleThreadExecutor();
String input = null;
try {
Future<String> result = ex.submit(consoleInputReadTask);
try {
input = result.get();
} catch (ExecutionException e) {
e.getCause().printStackTrace();
}
} finally {
ex.shutdownNow();
}
return input;
}
public void test() {
consoleInputReadTask = new ConsoleInputReadTask();
while ((line = readLine()) != null) {
// ...
}
You can stop consoleInputReadTask
by calling consoleInputReadTask.stop()
in another thread
来源:https://stackoverflow.com/questions/50394846/interrupt-system-console-readline