1

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

4

1 回答 1

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 套接字服务器。

于 2013-09-05T06:48:03.433 回答