有一个问题一直困扰着我一整天。考虑以下。此工作线程读取字符以解析命令,直到布尔值 _readingEnabled 为 false。该线程应该终止,但是当我查看调试器时,它变成了一个守护线程,并且由于始终应该只有一个连接而导致了问题。理想情况下,该线程应通过重新连接作为新线程重新启动,并且不应存在其他重复线程。
FileDownloaderActivity extends Activity{
TelnetClient _telnet;
Inputstream _in;
Outputstream _out;
boolean _readingEnabled = true;
onCreate(){
startReadThread();
}
startReadThread(){
Thread readingThread = new Thread(new Runnable(){
run(){
//connect _telnet, _in and _out
while(true){
if (_readingEnabled){
char c = in.read();
//some string operations
}
else{
break;
}
}
print("reading thread exited");
_readingEnabled = true ; //the thread will be restarted
});
}
readingThread.start();
}
}
我有另一个工作线程,它开始在 FileDownloaderActivity 的函数中下载文件。处理程序绑定到 UI 线程(有关系吗?)。该消息确实成功执行。
downloadFiles(){
Handler handler = new Handler(){ //part of the UI thread execution
void handleMessage(Message m){
startReadThread(); //restart the reading thread
}
}
Thread downloaderThread = new Thread(new Runnable(){
run(){
_readingEnabled = false; //should kick out of the while loop in the other thread
//download files...
handler.sendMessage(new Message());
}
});
}
我观察到的行为是新的 ReadingThread 在旧的 ReadingThread 终止之前开始执行。旧的 ReadingThread 确实打印出“读取线程已退出”,但它变成了一个守护线程。如果我继续做另一组下载的文件,我最终会得到两个守护进程读取线程,依此类推,直到连接严重失败。有任何想法吗?