I’m trying to write a loop which runs until I type a specific text in console where the application is running. Something like:
while (true) {
try {
System.out.println("Waiting for input...");
Thread.currentThread();
Thread.sleep(2000);
if (input_is_equal_to_STOP){ // if user type STOP in terminal
break;
}
} catch (InterruptedException ie) {
// If this thread was intrrupted by nother thread
}}
And I want it to write a line each time it pass through so I do not want it to stop within the while and wait for next input. Do I need to use multiple threads for this?
Yes.
Since using a
ScanneronSystem.inimplies that you’re doing blocking IO, one thread will need to be dedicated for the task of reading user input.Here’s a basic example to get you started (I encourage you to look into the
java.util.concurrentpackage for doing these type of things though.):