Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java console application: accepting commands from infinite loop

Tags:

java

console

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?

like image 425
Leisure Avatar asked Sep 07 '26 09:09

Leisure


2 Answers

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)

like image 83
morgano Avatar answered Sep 09 '26 22:09

morgano


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;
        }
    }



}
like image 26
orak Avatar answered Sep 09 '26 23:09

orak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!