Reputation: 557
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.
Upvotes: 1
Views: 243
Reputation: 8928
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.
Upvotes: 2