So I have an infinite loop running in the main thread of my console application like so.
public static void main(String[] args) {
while(true){
doSomething();
doSomethingElse();
System.out.println("some debugging info");
doAnotherThing();
}
}
I want this code to run over and over and over.
Once in a while, I would like to input a command into the console, such as the string "give me more info plox", and then if that command equals something, I want my code to do something.
Normally I would just use a scanner, but I can't do that here - since scanner.next(); pauses my code... I want my code to keep running whether or not I enter a command. The only workaround I can see is by using a file. But is there any other option?
Use threads, a main thread to read from console and another one to do the loop, the first thread updates a list of strings (producer) and the loop thread reads the list to see if there is something new for it (consumer)
You may do something like below
public class MainApp implements Runnable
{
static String command;
static boolean newCommand = false;
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
MainApp reader = new MainApp();
Thread t = new Thread(reader);
t.start();
while (true)
{
doSomething();
if (newCommand)
{
System.out.println("command: " + command);
newCommand = false;
//compare command here and do something
}
}
}
private static void doSomething()
{
try
{
System.out.println("going to do some work");
Thread.sleep(2000);
} catch (InterruptedException ex)
{
Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run()
{
Scanner scanner = new Scanner(System.in);
while(true)
{
command = scanner.nextLine();
System.out.println("Input: " + command);
newCommand= true;
}
}
}
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