我需要持续监听来 self 的 C# TCP 服务器的消息,所以我在单独的线程中执行:
private void StartMessageReceivingLoop()
{
new Thread(){
public void run()
{
String msg = null;
try
{
msg = inputStream.readLine(); // inputStream is a BufferedReader instance.
}
catch (IOException e)
{
e.printStackTrace();
}
if (msg != null && msg != "")
NotifyAndForwardMessage(msg); // Notify listeners about the message.
run(); // Next iteration.
}
}.start();
}
我的方法有什么问题?为什么我会收到 StackOverflowError?我猜测 run()
的调用速度非常快,因为 BufferedReader.readLine()
是非阻塞的,但我能做些什么呢?
最佳答案
不要在 run()
中调用 run()
。这不是递归函数。如果您想一直阅读直到出现某种情况,请将其包装在一个 while 循环中。通过在执行时调用正在执行的方法,您正在创建另一个堆栈框架。您真正想要的只是循环。
public void run() {
String msg = null;
while(true) { // Or whatever your exit condition is...
try {
msg = inputStream.readLine();
} catch(IOException e) {
// Handle properly.
}
if (msg != null && msg != "") {
NotifyAndForwardMessage(msg);
}
}
}
为了帮助说明,它的工作原理是这样的......
Thread.start()
+ run() // 1 (called by thread)
+ run() // 2 (called by previous run)
+ run() //3 (called by previous run)
+etc... where you'll eventually run out of stack space.
关于java - 监听来自 TCP 服务器的传入消息会导致 StackOverflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27771179/