开发者

Java input without pausing

开发者 https://www.devze.com 2023-04-06 07:06 出处:网络
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

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.


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


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.


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.


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.


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. ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号