Handle

小笔记:Handle

//这是Looper类中举例的一个用法。
 class LooperThread extends Thread {
     public Handler mHandler;
     public void run() {
         Looper.prepare();
         mHandler = new Handler() {
             public void handleMessage(Message msg) {
                 // process incoming messages here
             }
         };
         Looper.loop();
     }
 }

前段时间面试了一家公司,问到Handle的时候,面试官问到了同一个线程为何不允许创建多个Looper,又是怎么做到的时候,我愣了,于是现在自己捋一下这个过程。

在这里插入图片描述
然后来说说自己的理解。
Looper在类内维护了一个静态ThreadLocal,(这里简要的说一下ThreadLocal的作用,就是当你所存储的对象需要和当前线程绑定时使用),这样在每个线程取出的Looper就能保证是当前的线程对应的Looper啦。

public class ThreadLocal<T> {
    /**
     * ThreadLocals rely on per-thread linear-probe hash maps attached
     * to each thread (Thread.threadLocals and
     * inheritableThreadLocals).  The ThreadLocal objects act as keys,
     * searched via threadLocalHashCode.  This is a custom hash code
     * (useful only within ThreadLocalMaps) that eliminates collisions
     * in the common case where consecutively constructed ThreadLocals
     * are used by the same threads, while remaining well-behaved in
     * less common cases.
     */
    private final int threadLocalHashCode = nextHashCode();
    }
    /**
     * The next hash code to be given out. Updated atomically. Starts at
     * zero.
     */
    private static AtomicInteger nextHashCode =
        new AtomicInteger();
         /**
     * Returns the next hash code.
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }
	...
    }
public
class Thread implements Runnable {
	...
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
    ...
    }

PS:
1、这里在提一下每一个Thread都会有一个自己的ThreadLocalMap。所以在通过ThreadLocal取值时,就能在自己线程的ThreadLocalMap去获取,保证了每个线程的数据不会互相污染。
2、终于能改名字了,不再是"qq_xxxxxx"了,哈哈,逃

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值