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?
Without the Scanner class, reading user input with System.in is more complicated, and instead uses the InputStreamReader to convert data from bytes to characters. To do this, you must pass Java's System.in to the constructor of an InputStreamReader, and then pass that to the BufferedReader.
Do I need to use multiple threads for this?
Yes.
Since using a Scanner
on System.in
implies 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.concurrent
package for doing these type of things though.):
import java.util.Scanner;
class Test implements Runnable {
volatile boolean keepRunning = true;
public void run() {
System.out.println("Starting to loop.");
while (keepRunning) {
System.out.println("Running loop...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
System.out.println("Done looping.");
}
public static void main(String[] args) {
Test test = new Test();
Thread t = new Thread(test);
t.start();
Scanner s = new Scanner(System.in);
while (!s.next().equals("stop"));
test.keepRunning = false;
t.interrupt(); // cancel current sleep.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With