How to interrupt Java util. Scanner nextline call
•
Java
I'm using a multithreaded environment. A thread calls scanner repeatedly Nextline() to continuously listen for user input
Closing the stream doesn't seem to be an option because I'm from system In, which returns a non closable InputStream
Is there any way to interrupt the scanner so that it will return?
thank you
Solution
This article describes a method to avoid blocking when reading It gives code snippets that you can modify according to what I pointed out in my comments
import java.io.*; import java.util.concurrent.Callable; public class ConsoleInputReadTask implements Callable<String> { public String call() throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(system.in)); System.out.println("ConsoleInputReadTask run() called."); String input; do { System.out.println("Please type something: "); try { // wait until we have data to complete a readLine() while (!br.ready() /* ADD SHUTDOWN CHECK HERE */) { Thread.sleep(200); } input = br.readLine(); } catch (InterruptedException e) { System.out.println("ConsoleInputReadTask() cancelled"); return null; } } while ("".equals(input)); System.out.println("Thank You for providing input!"); return input; } }
You can use this code directly or write a new closable InputStream class combined with the logic described in this article
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码