我有一个 Transmitter 类,其中包含一个 BufferedReader 和一个 PrintWriter。这个想法是,在主类上,使用 Transmitter.receive() 和 Transmitter.transmit() 到主套接字。问题是:
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();
}
线程更改了“outputMessage”值,我可以使用辅助方法获取该值。问题是,如果没有 join,我的客户端会获取 outputMessage,但我想在我的主类上多次使用它,如下所示:
trans1.receive();
while(trans1.getOutput() == null);
System.out.println("message: " + trans1.getOutput());
但是使用 join 这个 system.out 永远不会执行,因为 trans1.receive()
卡住了......有什么想法吗?
编辑1:这里是发射器类https://titanpad.com/puYBvlVery
最佳答案
您可以发送\n
;这并不意味着您会在 Java 代码中看到它。
正如 Javadoc for BufferedReader.readLine()
中所述(强调我的):
(Returns) A String containing the contents of the line, not including any line-termination characters
因此“\n”
将永远不会被返回。
关于Java线程加入后卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37264319/