这里似乎已经提到了几次奇怪的问题。我有一个线程,也使用过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。有什么想法吗?
谢谢!
答案 0 :(得分:1)
可能的原因:
1)你已经产生了多个线程并且只关闭了其中一个。
2)在线程开始运行之前调用stopThread
。
3)线程在UI线程上排队了很多logTextView.append(logput)
个调用,因此 后来仍然在运行。