If I start reading from System.in
, it will block the thread until it gets data. There is no way to stop it. Here are all the ways that I've tried:
- Interrupting the thread
- Stopping the thread
- Closing
System.in
- Calling
System.exit(0)
does indeed stop the thread, but it also kills my application so not ideal. - Entering a char into the console makes the method return, but I can't rely on user input.
Sample code that does not work:
public static void main(String[] args) throws InterruptedException {
Thread th = new Thread(() -> {
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
});
th.start();
Thread.sleep(1000);
System.in.close();
Thread.sleep(1000);
th.interrupt();
Thread.sleep(1000);
th.stop();
Thread.sleep(1000);
System.out.println(th.isAlive()); // Outputs true
}
When I run this code, it will output true
and run forever.
How do I read from System.in
in an interruptible way?