ThreadLocal ——android消息机制handler在非主线程创建not called Looper.prepare() 错误的原因
引用自:https://www.jianshu.com/p/a8fa72e708d3
引出:
使用Handler的时候,其必须要跟一个Looper绑定。在UI线程可直接初始化Handler来使用。但是在非主线程中直接new Handler() 会报错: E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。 当初始化Handler的时候,其会通过Looper来获取当前的Looper,代码如下:
public Handler(Callback callback, boolean async) {
//省略
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//省略
}
那么,问题来了,为什么在子线程中,通过Looper.myLooper()方法获取的就是为空呢?如果有人回答了Looper是线程相绑定的,那它是如何做到绑定的? 如果还知道答案的话,那就可以跳过本篇文章了。
代码分析
1. Looper的myLooper方法
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
此方法只是通过从变量sThreadLocal中取出一个值。那么它的值是哪里来的呢?
2. Looper的prepare方法
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));
}
可以看出的是调用了这个方法之后,会在sThreadLocal中存在一个新建的Looper对象。那么看看这个sThreadLocal是什么东西呢?
ThreadLocal分析:
1. 定义 (本地线程副本变量工具类)
先看一下官方的解释:
Implements a thread-local storage, that is, a variable for which each thread
has its own value. All threads share the same {@code ThreadLocal} object,
but each sees a different value when accessing it, and changes made by one
thread do not affect the other threads. The implementation supports
{@code null} values.
这段话的意思是实现了一个线程相关的存储,即每个线程都有自己独立的变量。所有的线程都共享着这一个ThreadLocal对象,
并且当一个线程的值发生改变之后,不会影响其他的线程的值。
threadlocal是一个范型类,这标志着threadlocal可以存储所有数据,作为存储数据来说,我们首先想到的是会对外提供set(),get(),remove(),等方法,顺着我们的想法来看源码,果然如此。
2. 核心机制

ThreadLocal的核心机制:
- 每个Thread线程内部都有一个Map。
- Map里面存储线程本地对象(key)和线程的变量副本(value)
- 但是,Thread内部的Map是由ThreadLocal维护的,由ThreadLocal负责向map获取和设置线程的变量值。
3. 实现
ThreadLocal的类定义使用了泛型ThreadLocal<T>,其中T指代的是在线程中存取值的类型。(对应Android中使用的ThreadLocal, T则存放的类型为Looper)
- set方法
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
} ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
} void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
步骤:
1.获取当前线程的成员变量map
2.map非空,则重新将ThreadLocal和新的value副本放入到map中。
3.map空,则对线程的成员变量ThreadLocalMap进行初始化创建,并将ThreadLocal和value副本放入map中。
- get方法
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
} ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
} private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
} protected T initialValue() {
return null;
}
1.获取当前线程的ThreadLocalMap对象threadLocals
2.从map中获取线程存储的K-V Entry节点。
3.从Entry节点获取存储的Value副本值返回。
4.map为空的话返回初始值null,即线程变量副本为null,在使用时需要注意判断NullPointerException。
remove()方法
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
---------------------
Thread线程内部的Map在类中描述如下:
public class Thread implements Runnable {
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
}
总结
举例:
package test;
import test.*;
public class Test {
static final ThreadLocal<ThreadValue> mThreadLocal = new ThreadLocal<ThreadValue>();
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadValue threadValue = new ThreadValue("主线程");
mThreadLocal.set(threadValue);
System.out.print("in main thread : mThreadLocal:" + mThreadLocal +"\n");
System.out.print("in main thread : 名字:" + mThreadLocal.get().name +"\n");
mThreadLocal.get().print();
new Thread(new Runnable() {
@Override
public void run() {
ThreadValue childThreadValue = new ThreadValue("子线程");
mThreadLocal.set(childThreadValue);
System.out.print("in child thread : mThreadLocal:" + mThreadLocal +"\n");
System.out.print("in child thread : 名字:" + mThreadLocal.get().name +"\n");
mThreadLocal.get().print();
}
}).start();
}
}
package test;
public class ThreadValue {
String name;
public ThreadValue() {
}
public ThreadValue(String name) {
this.name=name;
}
public void print()
{
System.out.print("this = " + this+" \n");
}
}
结果:
然后编译:javac test/*.java
运行:java test.Test
输出:
in main thread : mThreadLocal:java.lang.ThreadLocal@788bf135
in main thread : 名字:主线程
this = test.ThreadValue@2b890c67
in child thread : mThreadLocal:java.lang.ThreadLocal@788bf135
in child thread : 名字:子线程
this = test.ThreadValue@4f93b604
可以看出由于mThreadLocal定义为静态最终变量,所以在主线程和子线程中,mThreadLocal都是同一个实例。
但是在两个线程中调用mThreadLocal.get(),得到的ThreadValue对象却并不相同。
这是因为mThreadLocal.get(),取到的对象是线程内的局部变量,相互之间并不干扰。
---------------------
作者:??-D-Luffy
来源:CSDN
原文:https://blog.csdn.net/zyfzhangyafei/article/details/64927617
版权声明:本文为博主原创文章,转载请附上博文链接!
ThreadLocal ——android消息机制handler在非主线程创建not called Looper.prepare() 错误的原因的更多相关文章
- Android消息机制——Handler
/**android的消息处理有三个核心类:Looper,Handler和Message.其实还有一个MessageQueue(消息队列), * 但是MessageQueue被封装到Looper里 ...
- Android消息机制
每一个Android应用在启动的时候都会创建一个线程,这个线程被称为主线程或者UI线程,Android应用的所有操作默认都会运行在这个线程中. 但是当我们想要进行数据请求,图片下载,或者其他耗时操作时 ...
- 在非主线程里面使用NSTimer创建和取消定时任务
为什么要在非主线程创建NSTimer 将 timer 添加到主线程的Runloop里面本身会增加线程负荷 如果主线程因为某些原因阻塞卡顿了,timer 定时任务触发的时间精度肯定也会受到影响 有些定时 ...
- Android消息机制:Looper,MessageQueue,Message与handler
Android消息机制好多人都讲过,但是自己去翻源码的时候才能明白. 今天试着讲一下,因为目标是讲清楚整体逻辑,所以不追究细节. Message是消息机制的核心,所以从Message讲起. 1.Mes ...
- Android开发之漫漫长途 ⅥI——Android消息机制(Looper Handler MessageQueue Message)
该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...
- Android开发之漫漫长途 Ⅶ——Android消息机制(Looper Handler MessageQueue Message)
该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...
- Android消息机制之ThreadLocal的工作原理
来源: http://blog.csdn.net/singwhatiwanna/article/details/48350919 很多人认为Handler的作用是更新UI,这说的的确没错,但是更新UI ...
- Android 进阶14:源码解读 Android 消息机制( Message MessageQueue Handler Looper)
不要心急,一点一点的进步才是最靠谱的. 读完本文你将了解: 前言 Message 如何获取一个消息 Messageobtain 消息的回收利用 MessageQueue MessageQueue 的属 ...
- Android消息机制探索(Handler,Looper,Message,MessageQueue)
概览 Android消息机制是Android操作系统中比较重要的一块.具体使用方法在这里不再阐述,可以参考Android的官方开发文档. 消息机制的主要用途有两方面: 1.线程之间的通信.比如在子线程 ...
随机推荐
- python oracle 查询返回字典
from: https://sourceforge.net/p/cx-oracle/mailman/message/27145597/ I'd do it with a "row facto ...
- Erlang 笔记
集成开发环境:IntelliJ IDEA的Erlang插件 教程:www.erlang-cn.com/462.html,寻找erlang程序设计第2版pdf f():释放之前绑定过的所有变量. -ex ...
- 跨域(四)——document.domain
浏览器有一个合法的性质:一个页面可以设置document.domain为当前子域或比当前子域更高级的域.一般顶级就到了根域,如果设置为其他域,浏览器就会报权限错误. 利用这个性质,我们可以通过设置do ...
- C#new出来的结构体内存分配在堆上
如题,有同事说因为结构体是值类型,所以 new出来的也是分配在栈上的.我的直觉是但凡使用new的东西都在堆上分配内存,除非C#对结构体做了特殊处理. new int[10]这个说明不了什么,因为数组是 ...
- php运行代码流程和性能优化方法
---恢复内容开始--- php文件->扫描->zd引擎去理解->opcodes->执行->输出 例子,用white随机循环20000数据进行性能测试,分别对比isset ...
- ORA-00600: internal error code, arguments: [4193]问题解决
操作环境 SuSE+Oracle11gR2 问题现象 单板宕机自动重启后,ORACLE运行不正常,主要表现如下: 1.执行shutdown immedate停止数据库时,提示ORA-00600: in ...
- 制作基于U盘启动和网络常识
一.制作基于U盘启动的操作系统盘1.准备相关的软件和硬件 下载软件并安装到[电脑]中 ——大白菜.老毛桃 硬件——U盘(空的) 2.插入U盘,点击桌面上的[大白菜装机版]打开大白菜, 点击[一键制作U ...
- spring boot 项目配置字符编码
- 编程四剑客sed-2019.2.20
sed [-Options] [‘Commands’] filename; sed工具默认处理文本,文本内容输出屏幕已经修改,但是文件内容其实没有修改,需要加-i参数即对文件彻底修 ...
- UVA11572-Unique Snowflakes-(最长不同连续子序列)
题意:给n个数,求最长不同连续子序列.n<=1e6. 解题过程: 1.记录数据存于数组 2.用左右指针l和r指向这段连续区间 3.右指针往右走,如果遇到没有存在于set集合的数就插入集合 否则左 ...