Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make thread skip read input operation from other thread

I have created 2 threads that works together for a socket connection: SocketIn and SocketOut (they are both working in a while(true) statement. In certain moments i need the SocketOut thread stop waiting for keyboard input a keep executing the following instructions even if he had read a null value and i need to do that without closing the thread or getting out the while(true). I have no idea on how to do that, so I need some advices.

like image 551
Vincenzo Scotti Avatar asked Mar 07 '26 05:03

Vincenzo Scotti


1 Answers

Look into CSP programming and BlockingQueues. You could use a Queue in your loop that accepts "commands". One of the command is input from the socket, the other command is input from the keyboard.

private final BlockingQueue<Command> inputChannel = new SynchronousQueue<>();

public void run() {
    while (true) {
        Command request = this.inputChannel.take();

        if (request instanceof Command.KeyboardInput) {
            ...

        } else {
            ...
        }
    }
}
like image 183
Fabian Zeindl Avatar answered Mar 09 '26 19:03

Fabian Zeindl