Search code examples
javamultithreadingconcurrencyjava-threads

Java thread stuck after join


I have this Transmitter class, which contains one BufferedReader and one PrintWriter. The idea is, on the main class, to use Transmitter.receive() and Transmitter.transmit() to the main socket. The problem is:

 public void receive() throws Exception {
      // Reads from the socket
      Thread listener = new Thread(new Runnable() {
        public void run() {
          String res;

          try {
            while((res = input.readLine()) != null) {
              System.out.println("message received: " + res);

              outputMessage = (res);

            if (res.equals("\n")) {
              break;
            }
           }
        } catch (IOException e) {
          e.printStackTrace();
        }
      };
    });

    listener.start();
    listener.join();
  }

The thread changes the 'outputMessage' value, which I can get using an auxiliary method. The problem is that, without join, my client gets the outputMessage but I want to use it several times on my main class, like this:

trans1.receive();
while(trans1.getOutput() == null);
System.out.println("message: " + trans1.getOutput());

But with join this system.out never executes because trans1.receive() is stuck... any thoughts?

Edit 1: here is the transmitter class https://titanpad.com/puYBvlVery


Solution

  • You might send \n; that doesn't mean that you will see it in your Java code.

    As it says in the Javadoc for BufferedReader.readLine() (emphasis mine):

    (Returns) A String containing the contents of the line, not including any line-termination characters

    so "\n" will never be returned.