【问题标题】:android daemon thread after thread exits out of a while loop线程退出while循环后的android守护线程
【发布时间】:2013-09-08 20:09:42
【问题描述】:

遇到一个问题困扰了我一整天。 考虑以下。此工作线程读取字符以解析命令,直到布尔值 _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 确实打印出“阅读线程已退出”,但它变成了一个守护线程。如果我继续下载另一组文件,我最终会得到两个守护进程读取线程,依此类推,直到连接严重失败。有什么想法吗?

【问题讨论】:

    标签: android multithreading handler message-queue


    【解决方案1】:

    如果您设置_readingEnabled = false 的唯一位置是downloaderThread.run(),那么您可以让 readingThread 无限期运行,即

              while(true){
                  if (_readingEnabled){
                     char c = in.read();
                     //some string operations
                    }
                 else{
                     Thread.sleep(100);
                    }
              }
    

    如果您的应用程序正在使用套接字,则使用Netty 可能会更成功。

    来自 Netty 主页:

    Netty 是一个 NIO 客户端服务器框架,可以快速轻松地开发网络应用程序,例如协议服务器和客户端。它极大地简化了网络编程,例如 TCP 和 UDP 套接字服务器。

    【讨论】:

    • 我想终止读取线程以避免套接字异常。由于某种原因,我使用 telnet 与之通信的服务器的性质使我的 telnet 客户端处于不良状态,这可以通过重新连接来解决(因此是新线程)。任何想法为什么我留下了守护线程?明天我会试试你的建议。谢谢,感谢您的意见:)
    • 嗯,好吧,也许你不需要使用Thread,如果你只是使用Thread来下载一些文件然后终止它,那么也许使用AsyncTask .它将允许您执行下载,完成后,您可以更新您的 UI,和/或执行您需要的任何处理。
    猜你喜欢
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多