另一个线程的代码怎么会在主线程上运行?

How could another thread's code run on the main thread?

最近被一些AndroidAPI弄糊涂了。这是一些简化的解释,因为代码有点长这是完全正确的,但只是让我感到困惑。

我有两个线程:UI 线程和另一个 HandlerThread 线程 AThread

mResponseHander 是在 UI 线程中创建的 Handler,它显然与 UI 线程的循环程序相关联。然后我将 mResponseHandler 传递给 AThread

AThread 是一个 HandlerThread 执行一些图像下载任务。在AThread中,我写了一些这样的代码:

mResponseHandler.post(new Runnable() {
        @Override
        public void run() {

            if (mRequestMap.get(target) != url) {
                return;
            }

            mRequestMap.remove(target);
            mThumbnailDownloadListener.onThumbnailDownloaded(target, bitmap);
        }
    });

此外,mRequestMapmThumbnailDownloadListener等变量只定义在AThread.

我知道当我调用 mResponseHandler.post(new Runnable) 时,Runnable 稍后会在 UI 线程上 运行,因为 mResponseHandler 与 UI 线程的循环程序。

问题来了:为什么在UI线程中运行ning上面的代码在mRequestMapmThumbnailDownloadListener等变量没有定义的情况下仍然正确在 UI 线程中但仅在 AThread?

中定义

why the code above running in the UI thread is still right when the variables "mRequestMap" and "mThumbnailDownloadListener" and others are not defined in the UI thread but only defined in the AThread?

任何 class 实例(让我们进一步使用 "object")驻留在 JVM heap(而不是 "in threads" 或其他任何地方)。将 new 运算符应用为

Type variableName = new Type();

在堆上分配了一块内存,并且对内存的引用存储为 variableName 的值。从现在开始,任何对象(例如 Thread 对象或实现 Runnable 的对象,就像您的情况一样)具有对 Type对象,可以"operate"就可以了。

话虽如此,通过将 Runnable 发布到与 UI 线程的 Looper 关联的处理程序,您告诉线程应该对那些对象完成什么工作驻留在堆中,可以被 mRequestMapmThumbnailDownloadListener 引用。

供参考:Java Memory Model.