关于handler,Looper和MessageQueue

非UI线程不能更新UI的根本原因

  如果对Android的View加载和绘制流程有一定了解就会知道,View的所有事件(measure,layout,draw)都是由 ViewRootImpl来管理的。Activity创建时会初始化ViewRootImpl(详细过程见我的这篇博客)。以View的invalidate为例,内部最终会调用到:

p.invalidateChild(this, damage);

  我们知道,Activity的根View是DecorView,也就是说最后会执行DecorView的invalidateChild方法。其实这还不是终点,终点在ViewRootImpl的invalidateChild中。因为在Activity初始化的时候,创建ViewRootImpl后调用了

view.assignParent(this);

  也就是把ViewRootImpl指定为了DecorView的parent。最终调用的是:

@Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        checkThread();
        ......
    }

  ViewGroup的addView同理。

mParent.requestLayout();

  会一直调用到ViewRootImpl的requestLayout方法,并在里面做线程检查。
  因此子线程调用会在这里抛出异常。


ThreadLocal

  ThreadLocal并不是Thread,它的作用是用来存储数据,并且保证这个数据在每个线程中只有一份。通过分析其get/set方法可以知道。

public void set(T value) {
        Thread t = Thread.currentThread();//当前线程
        ThreadLocalMap map = getMap(t);//看起来像是获取一个和当前线程有关的Map。
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

  set方法如上(API 21),通过分析知道,set方法中根据当前线程去获取某个ThreadLocalMap,然后往这个map中写入数据。看看getMap方法和createMap方法:

ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

  结果和我们上面的分析吻合,果然是获取的当前线程的ThreadLocalMap,然后将当前ThreadLocal作为键,要保存的变量作为值进行存储。
  再看一下get方法:

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();//这里会创建当前线程的ThreadLocalMap并存入默认值(null),返回null。
    }

  基本上很好理解,那么ThreadLocal的原理现在就可以总结出来了。就是用来存储作用域是线程的数据。并且每个ThreadLocal只能存储一个数据,但是每个线程可以拥有多个ThreadLocal。其根本原因是数据其实存储在当前线程的对象中,ThreadLocal对象作为键,数据作为值。


Looper

  Looper就像它的名字,主要负责循环并从消息队列中拿出消息。
  Looper在其类方法prepare()中初始化:

public static void prepare() {
        prepare(true);
    }

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

  这里有三个需要注意的地方:1.prepare会调用一个带boolean类型参数的prepare方法,这个跟主线程的Looper有关,下面会分析。2.在初始化Looper之前会先从当前线程的ThreadLocalMap中(sThreadLocal.get())试着获取Looper并抛出异常,这里确保了一个线程只能有一个Looper(Looper的构造方法是private类型)。3.sThreadLocal就是ThreadLocal的静态实例,这里在创建了Looper后立即保存在了ThreadLocal中,即一个线程对应一个Looper,Looper可以通过myLooper()获取。

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

  Looper的类变量中保存了MainLooper,也即主线程对应的Looper。

private static Looper sMainLooper;  // guarded by Looper.class


public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

  主线程的Looper在ActivityThread的main方法中初始化,并且loop方法也在main中调用。并且初始化了一个handler:

public static void main(String[] args) {
        ......

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

  在当前线程(UI线程初始化了Looper),然后初始化了handler,这里handler就和主线程Looper绑定了。具体绑定过程在handler的构造方法中,下面会介绍。最后调用Looper.loop(),代表当前应用跑起来了,整个应用可以理解为都是基于这个Looper和handler在运作,一旦Looper退出了,应用也就应该退出了。原因请看下面的loop方法分析:

public static void loop() {
        final Looper me = myLooper();//获取looper
        if (me == null) {//检查looper;
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//从looper中获取消息队列

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block//从消息队列中取消息,这个过程是阻塞式的。
            if (msg == null) {//唯一跳出循环条件
                // No message indicates that the message queue is quitting.
                return;
            }
            ......
            try {
                msg.target.dispatchMessage(msg);//消息交给handler处理
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ......
        }
    }

MessageQueue

   MessageQueue是消息队列,负责保存消息。上面的Looper就是负责从MessageQueue中取消息。MessageQueue在Looper初始化的时候被初始化:

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

  也就是说MessageQueue和Looper是相互绑定的关系。一个线程只能有一个Looper和MessageQueue。

   MessageQueue其主要有两个方法,分别是enqueueMessage和next。

boolean enqueueMessage(Message msg, long when) {
        ......
        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 {
                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;
            }
            ......
        }
        return true;
    }

  主要操作是把消息以链表的形式存起来。
  下面是next方法。

Message next() {
        ......
        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;//表示Looper的loop方法会收到null,loop循环退出
                }
            }
            ......
        }
    }

   大概就是从链表中取消息然后返回给looper。当没有消息时就一直循环,直到handler调用了enqueueMessage,这也就是阻塞的原理。

Handler

  handler用于进程间通信。其构造方法如下:

public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

  可以看到在handler初始化的时候调用了myLooper(),还记得这个方法吗?它的返回值是当前线程的Looper。如果当前线程没有准备Looper则会抛出异常。handler还有一个构造方法用于接收一个现有的looper:

public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

  看到这里其实有很多问题已经明白了,handler是怎么保证在其他线程将消息发回目标线程的。
  因为handler中绑定了一个looper,当使用handler发送消息时,会调用looper所对应的messageQueue的enqueueMessage方法。而这个线程也就是目标线程的looper一直在向messageQueue轮询message。
  还可以这样理解:我们在java中一般处理多线程是用锁的方式。其实堆内存是线程共享的,为了安全我们需要加锁。messageQueue相当于每个线程在堆中开辟的仓库。A线程要向B线程发消息,那么A线程就可以通过B线程的handler在A线程中往B在堆中的仓库扔消息,B线程是有looper来定时清理仓库的。因此感觉根本上还是通过堆来完成的线程通信。


Looper和MessageQueue

  handler在主线程可以直接使用,因为系统已经帮我们调用了Looper.prepare()和Looper.loop(),若在子线程中想要使用handler来实现其他线程向子线程发送消息,则要手动调用这两个方法,否则会抛出异常。


UI线程(ActivityThread)

  其handler在ActivityThread类中被创建

    final H mH = new H();//作为ActivityThread的常量,在创造ActivityThread对象时被初始化。

  其Looper在main方法中Looper.prepareMainLooper();中被创建,并保存在ThreadLocal中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值