Reputation: 350
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?
Upvotes: 6
Views: 16404
Reputation: 421040
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.
}
}
Upvotes: 5
Reputation: 81084
Yes, you would need two threads for this. The first could do something like this:
//accessible from both threads
CountDownLatch latch = new CountDownLatch(1);
//...
while ( true ) {
System.out.println("Waiting for input...");
if ( latch.await(2, TimeUnit.SECONDS) ) {
break;
}
}
And the other:
Scanner scanner = new Scanner(System.in);
while ( !"STOP".equalsIgnoreCase(scanner.nextLine()) ) {
}
scanner.close();
latch.countDown();
Upvotes: 0