Android之为什么一个线程只有一个Handler,Looper

本文深入剖析了Android中Looper的工作机制,解释了为何一个线程只能拥有一个Looper实例,并通过源码展示了Looper、MessageQueue及Handler之间的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前在讲Handler原理点我的时候,最后做了一个总结,一个现在只有一个Handler,Looper…,如下图:
这里写图片描述

但是一直没有搞清楚为什么?Why?
最近偶然翻源码,终于是找到了原因:

全局静态的变量sThreadLocal 用来保存Looper对象(就相当于一个Map集合,键位当前的Thead线程,值为Looper对象)

public final class Looper {
65    private static final String TAG = "Looper";
66
67    // sThreadLocal.get() will return null unless you've called prepare().
68    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
69    private static Looper sMainLooper;  // guarded by Looper.class
71    final MessageQueue mQueue;
72    final Thread mThread;
73
74    private Printer mLogging;
75

再看Looper创建的地方:

 public static void prepare() {
83        prepare(true);
84    }
85
86    private static void prepare(boolean quitAllowed) {

      // 这里是关键,如果这个线程已经存在Looper报异常
87        if (sThreadLocal.get() != null) {
88            throw new RuntimeException("Only one Looper may be created per thread");
89        }
      // 不存在,创建一个Looper设置到sThreadLocal
90        sThreadLocal.set(new Looper(quitAllowed));
91    }

从Looper的创建的地方,我们知道一个线程只有一个Looper,那MessageQueue,Handler只有一个也就不奇怪了。


ps:在子线程new Handler,如下:


33  * <p>This is a typical example of the implementation of a Looper thread,
34  * using the separation of {@link #prepare} and {@link #loop} to create an
35  * initial Handler to communicate with the Looper.
36  *
37  * <pre>
38  *  class LooperThread extends Thread {
39  *      public Handler mHandler;
40  *
41  *      public void run() {
42  *          Looper.prepare();
43  *
44  *          mHandler = new Handler() {
45  *              public void handleMessage(Message msg) {
46  *                  // process incoming messages here
47  *              }
48  *          };
49  *
50  *          Looper.loop();
51  *      }
52  *  }</pre>
总结

多看源码,知识的源头是不尽的财富!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值