views:

714

answers:

5

I was just wondering how i would let my java program continue running, but always be ready to take input.

Right now i am using a bufferreader and reading in a line, but that makes my program halt and wait for input. I want the program to continue running but be ready to take input whenever needed, is there a way to do this?

+10  A: 

I would expect that you're going to have to look into multithreading your application in order to get this working as you desire.

Edit: Of course, while this functionality can be achieved by a purely CLI interface, you would probably be better off exploring other options (i.e. GUI options) if you intend on having a full response/event-driven system running in a multithreaded fashion.

James Burgess
I have found threading to be somewhat complicated, don't get discouraged by it though, it's definitely up there in complexity. Try something else for a while if you do.
Organiccat
ive got nothing but time to play around and learn it, thanks
Petey B
The comment about CLI interfaces seems like a red herring to me. It's entirely possible to have a program with a "CLI interface" that is able to process user input while still doing other stuff in the background. Take the program "top", for example.
Laurence Gonsalves
You're quite right, Laurence, however, I had presumed (and will clarify in my post above, by editing) that the user was aiming for a more event-driven response system by the way that the question was phrased. I'll update my 'edit'.
James Burgess
+1  A: 

I think your program will have to occasionally poll for user input.

Galwegian
+1  A: 

Give it a nice multi-threaded GUI instead of a CLI :)

willcodejavaforfood
A: 

I agree with James, another alternative is "faking" continuous program running. This won't work with all scenarios, but you can set a timer right before you display the user input, then calculate the time between stop and "start" again when the user inputs something.

Use that time to perform a repeated function a certain number of times. This is only helpful if you've got something on a timer itself already, like a constantly draining integer every few seconds.

An example:

You ask the user a question but only want to give them 5 seconds to answer. When the user answers (hits enter) the program will compute the time it took them to enter, if too long, throw one message, if under the time limit throw another.

I'm only suggesting this method because threading, which is what you really want to get into, is quite advanced.

Organiccat
+2  A: 

Here is a quick example of how a multi-threaded command line interface application may work. This will not require polling for input, nor a GUI interface in order to perform tasks in the background while waiting for input from a user in a console.

In this example, a Thread is running in the background, which can be told to output a greeting in a specified number of seconds later.

public class CommandLineMultiThread
{
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);

        // Makes and runs the background thread.
        MyThread myThread = new MyThread();
        Thread t = new Thread(myThread);
        t.start();

        // Get the number of seconds to wait from the console.
        // Exit when "0" is entered.
        int waitDuration;
        do
        {
            waitDuration = s.nextInt();
            myThread.setGreetIn(waitDuration);

        } while (waitDuration != 0);

        myThread.quit();
    }

    static class MyThread implements Runnable
    {
        boolean running = true;                // Boolean to keep thread alive.
        long greetingTime = Long.MAX_VALUE;    // Time to greet at.

        public void setGreetIn(int i)
        {
            greetingTime = System.currentTimeMillis() + (i * 1000);
        }

        public void quit()
        {
            running = false;
        }

        public void run()
        {
            while (running)
            {
                if (System.currentTimeMillis() > greetingTime)
                {
                    System.out.println("Hello!");
                    greetingTime = Long.MAX_VALUE;
                }

                try
                {
                    Thread.sleep(100);
                }
                catch (InterruptedException e) {}
            }
        }
    }
}

The Scanner class can be used to accept user input from the command line interface by routing the input from the System.in object.

Then, while the background thread myThread is running, the main thread is waiting for an input from System.in via the Scanner.nextInt method. Once the seconds to wait has been accepted, the background thread is told to wait until a certain time, and once that time arrives, the greeting Hello! is output to the console.

coobird