【问题标题】:Android - Stopping a thread using a while loopAndroid - 使用 while 循环停止线程
【发布时间】:2011-09-09 16:34:27
【问题描述】:

这里似乎已经提到过几次奇怪的问题。我有一个线程,也使用了 AsyncTask,我正试图让它停止运行,根据用户的请求。 所以,很自然地,我在 while 循环中使用了一个布尔值。线程始终将布尔值视为 true,即使它在其他地方打印 false。

代码如下,感谢任何帮助!

/**
 * Opens new socket and listens on the specified port until a user stops the thread, the logview is updated with messages
 */
public void run() {
    byte[] receiveData = new byte[1024];
    byte[] sendData = new byte[1024];
    Log.e("Text2Server", "Starting Server");
    this.running = true;
    while(this.running) {
        Log.i("Text2Server", "Server should be running: " +  running);
        try {
            serverSocket = new DatagramSocket(port);
        } catch (SocketException e1) {
            e1.printStackTrace();
        }
        try {   
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            final String fromIP = new String(receivePacket.getAddress().toString());
            final int fromPort = receivePacket.getPort();
            final String received = new String(receivePacket.getData());
            Date now = new Date();
            final String logput = DateFormat.getDateTimeInstance().format(now) + " - Message from: " + fromIP + " through Port: " + fromPort + " with Message: " + received;
            Log.i("Text2Server", logput);
            //All UI Operations are done in this thread
            uiHandler.post(new Runnable(){
                @Override
                public void run() {
                    logTextView.append(logput);
                }                   
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    serverSocket.close();
}

public void stopThread() {
    this.running = false;
    Log.i("Text2Server", "Stopping Server, value is now: " + running);
}

调用 stopThread() 会使其为 false,但线程仍会进入 while 并打印出 true。有什么想法吗?

谢谢!

【问题讨论】:

  • 你是怎么调用 stopThread 的?
  • 从一个活动中,我创建了一个线程实例,将其设置为在该活动中运行,然后在用户按下按钮时调用 stopThread()
  • 在日志中显示“running”的值而不是“this.running”...
  • 是的,试过了。它们都是相同的值,我只是在检查中途发布,看看它是否有所作为。可以肯定的是,甚至将运行声明为 volatile。
  • 你确定它没有被serverSocket.receive(receivePacket);屏蔽?

标签: android multithreading networking udp


【解决方案1】:

可能的原因:

1) 你产生了多个线程并且只关闭了其中一个。

2) 在线程开始运行之前调用stopThread

3) 该线程已将 UI 线程上的许多 logTextView.append(logput) 调用排队,因此似乎之后仍在运行。

【讨论】:

  • 也许在while循环之后添加一个日志输出来仔细检查第三种可能性。
  • 谢谢,第三种可能性的日志输出仍然显示,虽然它似乎没有更新文本视图,但这是另一个问题。活动只产生一个线程,并且仅在收到至少一条消息后才调用停止线程。这是一个奇怪的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
相关资源
最近更新 更多