0

How would I make a sort of console for my program without pausing my code? I have a loop, for example, that needs to stay running, but when I enter a command in the console, I want the game to check what that command was and process it in the loop. The loop shouldn't wait for a command but just have an if statement to check if there's a command in the queue.

I'm making a dedicated server, by the way, if that helps.

1
  • Are you using Swing? You can just attach an event listener to a textfield for command entry. Or is this "game" not using Swing? (You did say "server"....) Commented Sep 21, 2011 at 18:21

5 Answers 5

2

Have them run in two separate threads.

class Server {

    public static void main(String[] args) {
        InputThread background = new InputThread(this).start();
        // Run your server here
    }
}

class InputThread {
    private final Server server;
    public InputThread(Server server) {
        this.server = server;
    }

    public void run() {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()) {
            // blocks for input, but won't block the server's thread
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

There's pretty obvious approach: use a dedicated thread to wait on InputStream, read events/commands from it and pass them into a queue.

And your main thread will be regularly checking this queue. After every check it will either process a command from the queue or continue what it was doing if it's empty.

Comments

2

What you'd like to have is a thread in which you keep the command reading code running. It'd probably look something like this:

class ReadCommand implements Runnable
{
    public void run()
    {
       // Command reading logic goes here
    }
}

In your "main" thread where the rest of the code is running, you'll have to start it like this:

new Thread(new ReadCommand())).start()

Additionally, you need a queue of commands somewhere which is filled from ReadCommand and read from the other code. I recommend you to read a manual on concurrent java programming.

Comments

1

The server should run in its own thread. This will allow the loop to run without pausing. You can use a queue to pass commands into the server. Each time through the loop the server can check the queue and process one or more commands. The command line can then submit commands into the queue according to its own schedule.

Comments

0

You can read from the console in a separate thread. This means your main thread doesn't have to wait for the console.

Even server applications can have a Swing GUI. ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.