gpt4 book ai didi

Android - 使用 while 循环停止线程

转载 作者:行者123 更新时间:2023-11-30 04:33:01 25 4
gpt4 key购买 nike

奇怪的问题似乎在这里被提到过几次。我有一个线程,也使用了 AsyncTask,我正试图根据用户的请求让它停止运行。所以,很自然地,我在 while 循环中使用了一个 bool 值。该线程始终将该 bool 值视为 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。有什么想法吗?

谢谢!

最佳答案

可能的原因:

1) 您已经生成了多个线程并且只关闭了其中一个。

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

3) 该线程已在 UI 线程上排队等待许多 logTextView.append(logput) 调用,因此看起来之后仍在运行。

关于Android - 使用 while 循环停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7364779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com