停止其中有阻塞调用的 HandlerThread
Stop HandlerThread which has a blocking call in it
我正在通过 TCP/IP 发出网络请求并在单独的线程上收听响应。每次进行网络调用时,我都想停止正在侦听响应的先前线程并进行新线程。
不幸的是,旧的 HandlerThread 在启动新的 HandlerThread 之前没有终止。
if (mHandler != null) {
mHandler.getLooper().quit();
}
if (mHandlerThread != null) {
mHandlerThread.interrupt();
mHandlerThread.quit();
}
mHandlerThread = new HandlerThread("socket-reader-thread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mHandler.post(() -> {
try {
String line;
while ((line = mBufferedReader.readLine()) != null) // BLOCKING CALL
{
...
}
mBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
});
有办法终止这些 HandlerThread
吗?
mHandlerThread.quit();
这行代码只会退出处理线程的循环程序,这并不意味着它会立即终止线程,因为你 post执行 while 循环的消息。如果消息 while 循环不停止,则 mHandlerThread 将永远不会停止。所以你可以这样改变你的代码:
mHandler.post(() -> {
try {
String line;
while (!mHandlerThread.isInterrupted && (line = mBufferedReader.readLine()) != null)
{
...
}
mBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
});
只需添加 !mHandlerThread.isInterrupted()
作为组合的 while 循环条件。
顺便说一句,你不需要打电话:
if (mHandler != null) {
mHandler.getLooper().quit();
}
但是mHandlerThread.interrupt();
是必须的!
我正在通过 TCP/IP 发出网络请求并在单独的线程上收听响应。每次进行网络调用时,我都想停止正在侦听响应的先前线程并进行新线程。
不幸的是,旧的 HandlerThread 在启动新的 HandlerThread 之前没有终止。
if (mHandler != null) {
mHandler.getLooper().quit();
}
if (mHandlerThread != null) {
mHandlerThread.interrupt();
mHandlerThread.quit();
}
mHandlerThread = new HandlerThread("socket-reader-thread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mHandler.post(() -> {
try {
String line;
while ((line = mBufferedReader.readLine()) != null) // BLOCKING CALL
{
...
}
mBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
});
有办法终止这些 HandlerThread
吗?
mHandlerThread.quit();
这行代码只会退出处理线程的循环程序,这并不意味着它会立即终止线程,因为你 post执行 while 循环的消息。如果消息 while 循环不停止,则 mHandlerThread 将永远不会停止。所以你可以这样改变你的代码:
mHandler.post(() -> {
try {
String line;
while (!mHandlerThread.isInterrupted && (line = mBufferedReader.readLine()) != null)
{
...
}
mBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
});
只需添加 !mHandlerThread.isInterrupted()
作为组合的 while 循环条件。
顺便说一句,你不需要打电话:
if (mHandler != null) {
mHandler.getLooper().quit();
}
但是mHandlerThread.interrupt();
是必须的!