有一个问题困扰了我一整天。 考虑以下。此工作线程读取字符以解析命令,直到 bool 值 _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 的函数内开始文件下载。处理程序绑定(bind)到 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 确实打印出“读取线程已退出”,但它变成了守护线程。如果我继续执行另一组下载文件,我最终会得到两个守护进程读取线程,依此类推,直到连接严重失败。有什么想法吗?
最佳答案
如果您设置 _readingEnabled = false
的唯一位置是在 downloaderThread.run()
中,那么您可以让 readingThread 无限期地运行,即
while(true){
if (_readingEnabled){
char c = in.read();
//some string operations
}
else{
Thread.sleep(100);
}
}
如果您的应用程序正在使用套接字,则使用 Netty 可能会更成功.
来自 Netty 主页:
Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server.
关于线程退出 while 循环后的 android 守护进程线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18628740/