简体   繁体   中英

Blocking the output until input is finished using threads java

I'm making a simple console chat application using sockets and threads. I have two different threads for sending and reading the messages. Everything works fine except one thing. I have to block the reader thread if I'm currently inside the sending thread.

@Override
public void run() {
    input = In.readLine();

    while (!input.equals("x")) {
        if (input.isEmpty()) {
            Out.println("----------------------------");
            Out.print("Your message: ");
            message = In.readLine();
            Out.println("----------------------------");

            writer.println(message);
            writer.flush();
        }

        input = In.readLine();
    }
}

Here is the reading thread

@Override
public void run() {
    try {
        while ((receivedMessage = reader.readLine()) != null) {
            Out.println("Received message: " + receivedMessage);
        }
    } catch (IOException ex) {

    }
}

What I have to do is following: If I'm currently writing a message "message = In.readLine()", and in the meantime I receive some messages, these should be displayed only after I finish the input.

There are a variety of ways to do this. Perhaps the simplest would be to use a monitor to lock display of received messages while typing a message to be sent. Basically have an Object - you could call it displayLock or something like that - and put within blocks synchronizing on this Object the first four lines of the if block in the sending thread and the Out.println line in the receiving thread. That way only one of the two synchronized blocks could proceed at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM