Android中的线程间通信(Handler与Looper)

Java中的线程回顾

在操作系统的概念里,进程是具有一定独立功能的程序、它是系统进行资源分配调度的一个独立单位。
在Java的虚拟机中,进程拥有自己独立的虚拟地址空间(准确的说是方法区和堆内存)。
而线程则是CPU调度的基本单元,它没有自己独立的虚拟地址空间,它依附于进程的虚拟地址空间。在Java虚拟机中,线程拥有的不过是PC计数器和方法栈而已。
在Android系统中,进程之间的通信称为IPC,它主要由Binder完成,线程之间由于共享地址空间,各线程都可以对对象进行操作,因此线程间的通信机制更为简单,由轻便的Handler和Looper完成。

线程独有数据

由于同一个进程的线程共享资源,因此,如何保证数据在某线程的私有性变为极为重要,忽略这点会造成著名的多线程同步问题。在Java中,线程被封装为Thread类,一种很常见的思维是维护一个共有的哈希表,然后将线程的私有变量存储起来,当线程需要取用数据时,从哈希表中读取私有数据。

    val threadData = ConcurrentHashMap<Thread,Any>()

但是如果这样的话,程序员就需要自己在程序中维护这么一个表,且不说自己能不能记住到底存储了什么,光是表的维护就已经很麻烦了,而且表的更新特别耗费资源。因此,比较好的方法是将数据存储封装在Thread这个类的内部,由于每一个线程都是一个Thread对象,它们需要这个值的时候直接读取其内部的值即可。Android采用了ThreadLocal这个类,实现了在指定线程中存储数据的功能。
首先我们来看一下ThreadLocal类怎么使用:

    fun test()
    {
        val localAge = ThreadLocal<Int>() // 申请一个Int类型的线程私有变量
        localAge.set(10) //主线程中修改值
        Log.d(Thread.currentThread().toString(),localAge.get().toString()+"-> $localAge")
        Thread({
            localAge.set(12345) //其他线程中修改值
            Log.d(Thread.currentThread().toString(),localAge.get().toString()+"-> $localAge")
        }, "Thread#2").start()
        Thread({
            localAge.set(18) //其他线程中修改值
            Log.d(Thread.currentThread().toString(),localAge.get().toString()+"-> $localAge")
        },"Thread#3").start()

        localAge.set(-33) //主线程中第二次修改值
        Log.d(Thread.currentThread().toString(),localAge.get().toString()+"-> $localAge")
    }

输出结果:

01-09 21:33:50.274 11935-11935/cn.suiseiseki.www.androidstudy D/Thread[main,5,main]: 10-> java.lang.ThreadLocal@4368aaa8
01-09 21:33:50.274 11935-11950/cn.suiseiseki.www.androidstudy D/Thread[Thread#2,5,main]: 12345-> java.lang.ThreadLocal@4368aaa8
01-09 21:33:50.279 11935-11935/cn.suiseiseki.www.androidstudy D/Thread[main,5,main]: -33-> java.lang.ThreadLocal@4368aaa8
01-09 21:33:50.279 11935-11951/cn.suiseiseki.www.androidstudy D/Thread[Thread#3,5,main]: 18-> java.lang.ThreadLocal@4368aaa8

可以看到,在不同线程中访问同一个Thread对象,其获取的值不一样,这就是ThreadLocal的奇妙之处
下面我们分析一下ThreadLocal的主要方法:

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

其实代码已经很明显了,就是通过不同的Thread对象获取其Thread内部维护的ThreadLocalMap,然后查询是否有这个参数,如果有就返回这个参数的值,如果没有则返回null.对于set方法来说,首先查找线程是否创建了ThreadLocalMap,如果没有则创建之,然后就是正常的map操作了
如果你感兴趣的话,可以再深入了解一下ThreadLocalMap这个类,它内部采用弱引用维护了一个哈希表,这里不再详细介绍。
总之,现在我们已经知道,多个线程之间确实可以互不干扰地存储和修改某些数据,这是线程间通信的基础。

MessageQueue:消息队列

Android中的线程间通信涉及到四个组件:Handler,Looper,Message,MessageQueue

MessageQueue称为消息队列,得力于上文所述的ThreadLocal类,现在每一个线程可以拥有自己的MessageQueue了。MessageQueue通过一个单链表来维护一个消息队列,因为单链表在插入和删除过程中有性能优势。作为一个队列,它自然有两个方法,用于入队(插队)的enqueueMessage方法和出队的next方法

    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

可以看到,enqueueMessage方法先检查Message的合法性,然后再根据Message的when属性将Message插入单链表中。

Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

next方法是一个无限循环的方法,如果MessageQueue队列中没有消息,此方法会堵塞,直到新的消息到来位置,它会将消息取出,然后再链表中删除它。

Looper:MessageQueue的使用者

有了消息队列之后,我们还需要一个使用消息队列的对象:Looper。从Looper的名字可以看出,它代表某种循环的意思。为了让某个线程能不断地处理消息(Message),我们就需要为线程创建Looper:

        Thread(
                {
                    Looper.prepare()
                    val handler = Handler()
                    Looper.loop()
                }
        ).start()

注意这里需要调用Looper的静态方法。当然,我们也可以随时停止Looper,在线程中调用quit或者quitSatety即可:

                    Looper.myLooper().quit()
                    Looper.myLooper().quitSafely()

可以看到,Looper的主要方法都是静态方法,便于我们在线程的任意位置调用它们
Looper内部最重要的方法就是loop()方法,它是一个死循环,跳出循环的唯一方式是其MessageQueue的next返回了null(正常情况下应该是被堵塞的)。当Looper调用quit或者quitSafely时,它会通知消息队列退出,使其返回null值。
如果MessageQueue的next返回了Message消息,它会将这个消息交给Handler去处理。

Handler:消息的发送与处理者

Handler的工作就是发送消息和处理消息,它主要通过两个方法:sendMessage和post(runnable)去发送消息
它们的底层过程就是向消息队列中插入一条消息,通过Looper接收后又交给了它自己的dispatchMessage方法去处理:

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

首先,它会检查消息本身的callback是否为空(这适用于post方法发送的runnable对象消息),如果不为空则由这个runnable对象接管执行。
如果为空,再检查本Handler自身的mCallback是否为空,如果不为空则由这个对象代为处理。
如果mCallback也为空,则在自身的handleMessage方法中执行了,这是常规操作,自己在Handler的子类中实现这个方法即可

Handler还有一个很方便的构造方法,传入一个指定Looper来构造Looper:

    public Handler(Looper looper) {
        this(looper, null, false);
    }

比如 val handler = Handler(Looper.getMainLooper()),快速在其他线程中获取主线程的handler

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容