android_ThreadLocal

来源:互联网 发布:冰岛旅游 知乎 编辑:程序博客网 时间:2024/06/06 11:04

ThreadLocal

1. ThreadLocal 是什么?

/** * 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. * @see java.lang.Thread * @author Bob Lee */

源码中解释到 ThreadLocal 就用于存储数据,每一个线程都会一个数据的拷贝,每一个线程获取到值都是不一样的,并且当前线程修改之后,不会应到其他线程。

2. ThreadLocal 的作用?

这里举例解释 ThreadLoal 在andorid 源码的应用。使用Handler就必须获取当前线程的 Looper 对象,而每一个线程的 Looper 是不一致的,所以说使用 ThradLocal 去保存和获取当前线程的 Looper 就可以达到这个的效果。

3. 下面举例说明 ThreadLocal 存储的数据在各个线程中是不会相互干扰的。

具体 ThreadLocal 在 Handler 的应用关注adnroid_Handler消息发送处理机制:http://blog.csdn.net/lwj_zeal/article/details/52814068#t16

// 创建一个ThreadLocalfinal ThreadLocal<String> threadLocal = new ThreadLocal<>();//在主线程中设置threadlocal的值为"hello"threadLocal.set("hello");String msg = threadLocal.get();Log.e("zeal","主线程:"+ msg);//在子线程中操作new Thread(){    @Override    public void run() {        super.run();        threadLocal.set("android");        String msg = threadLocal.get();        Log.e("zeal", "线程"+Thread.currentThread().getName()+":" + msg);    }}.start();//在子线程中操作new Thread(){    @Override    public void run() {        super.run();        String msg = threadLocal.get();        Log.e("zeal", "线程"+Thread.currentThread().getName()+":" + msg);    }}.start();运行结果:主线程:hello线程Thread-172:android线程Thread-173:null

运行结果说明不同线程取出之前保存的值是不尽相同的,也就是即使在某一线程修改了这个ThreadLocal保存的值,也是不会相互干扰到其他线程的。

4. ThreadLocal 的内部实现原理

4.1 通过 set 为ThreadLocal 设置值

public void set(T value) {    Thread currentThread = Thread.currentThread();    Values values = values(currentThread);    if (values == null) {        values = initializeValues(currentThread);    }    values.put(this, value);}
void put(ThreadLocal<?> key, Object value) {    ...    table[index] = key.reference;    table[index + 1] = value;    size++;    ...}
Values values(Thread current) {    return current.localValues;}
Values initializeValues(Thread current) {    return current.localValues = new Values();}

将当前线程封装成一个 Values 对象,然后以 ThreadLocal 为 key, 需要添加的value 为值添加到 values 中的。注意在 put 方法中 ThreadLoca 的值是存储在 ThreadLoal 内部一个 table 数组中的,并且存储位置为 ThreadLocal.Reference 角标的下一个位置。

4.2 通过 get 的方式获取保存的 ThreadLocal 值

public T get() {    // Optimized for the fast path.    Thread currentThread = Thread.currentThread();    Values values = values(currentThread);    if (values != null) {        Object[] table = values.table;        int index = hash & values.mask;        if (this.reference == table[index]) {            return (T) table[index + 1];        }    } else {        values = initializeValues(currentThread);    }    return (T) values.getAfterMiss(this);}

获取当前的线程对应的Values,其实这个 Values 就是 Thread 中的一个属性值 ThreadLocal.Values localValues,如果为null,那么通过initializeValues(currentThread) 给当前线程的 localValues 赋值。否则获取存储 ThreadLocal 值的 table 数组,判断table中是否存在 ThreadLocal 设置的值。如果没有则返回null;

5. 得出的结论

ThreadLocal 中 set 和 get 操作的都是对应线程的 table数组,因此在不同的线程中访问同一个 ThreadLocal 对象的 set 和 get 进行存取数据是不会相互干扰的。

0 0
原创粉丝点击