---
title: "Handler 消息机制分析"
author: "小桔子"
date: "2015-12-18T16:54:42Z"
tags: ["Android", "Handler", "Looper", "ThreadLocal"]
categories: ["移动开发"]
slug: "handler"
draft: false
lastmod: "2015-12-18T16:54:42Z"
id: 2265068
url: "https://824685523.iteye.com/blog/2265068"
---

Handler消息分析

ThreadLocal sThreadLocal =new ThreadLocal();  
是什么鬼，存放数据的工具，当前线程存放的数据，别的线程获取不到  
这个类提供get和set方法，比如在A线程中sThreadLocal.set("value");B线程中打印 sThreadLocal.get();打印出来为空。原因这边博文上分析得很清楚：  
[http://blog.csdn.net/singwhatiwanna/article/details/48350919](http://blog.csdn.net/singwhatiwanna/article/details/48350919)；

关于 Handler Looper 以及MessageQueue的关系：  
hreadLocal中存放Looper对象，每个Looper对象绑定得有一个MessageQueque。  
通常handler对象在创建的时候会创建looper以及messageQueue，在ui线程中，这个创建的方法已经自动创建了，所以通常我们不去创建。而如果handler对象在子线程中则需要调用Looper.prepare();

Looper够构造器  
private Looper(){  
      mQueue=new MessageQueue(); //可看出创建looper对象时也创建了messageQuere()对象  
      mRun=true;  
     mThread=Thread.currentThread();  
}

Looper的prepare方法  
public static final void prepare(){  
if(sThreadLocal.get()!=null){  
throw new RuntimeException("Only one Looper may be created per thread");  
}  
sThreadLocal.set(new Looper());//线程中调用Looper.prepare();方法时创建了looper，这里的looper对象存放在sThreadLocal中，独立属于当前线程  
}

Looper的方法源码 使用先进先出的方式去读取messagequeue中的消息。