【问题标题】:Stop HandlerThread which has a blocking call in it停止其中有阻塞调用的 HandlerThread
【发布时间】:2019-11-12 15:37:51
【问题描述】:

我正在通过 TCP/IP 发出网络请求并在单独的线程上监听响应。每次进行网络调用时,我都想停止上一个正在监听响应的线程并创建一个新线程。

不幸的是,旧的 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();
                }
            });

有没有办法终止这些HandlerThreads?

【问题讨论】:

    标签: android multithreading performance android-handlerthread


    【解决方案1】:

    mHandlerThread.quit(); 这行代码只会退出处理线程的looper,这并不意味着它会立即终止线程,因为您发布了一条执行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(); 是必需的!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 2018-01-28
      • 1970-01-01
      相关资源
      最近更新 更多