理解ThreadLocal

来源:互联网 发布:网络销售模式 编辑:程序博客网 时间:2024/05/16 04:35

参考
正确理解TheadLocal
解密ThreadLocal
JDK文档
ThreadLocal


线程同步机制:

目的:解决多线程中相同变量的访问冲突问题。
在同步机制中,通过对象的锁机制保证同一时间只有一个线程访问变量。这时该变量是多个线程共享的。
使用同步机制要求程序慎密地分析什么时候对变量进行读写,什么时候需要锁定某个对象,什么时候释放对象锁等繁杂的问题。
经典案例:多生产者和多消费者。


ThreadLocal:

ThreadLocal的作用是提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度。

ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。(ThreadLocalVariables可能更好理解点

个人理解:每个线程中各自用独立的对象。可以很方便的获取在本线程中存储的对象,拍案惊奇!!!应该要有一个ThreadLocalMananger,保持ThreadLocal为单例,在Handler机制里面Looper中为static final,被所有线程中Looper共享。

当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候,可以考虑采用ThreadLocal。


源码:

android中源码ThreadLocal中。

  • Thread中持有TreadLocal.Values,
  • 每一个线程就有一个Values,所以每一个线程都有Object[]数组 table。通过数组角标来获取该线程局部变量。
//Sets the value of this variable for the current thread.//给当前线程设置数据(泛型T)public void set(T value) {    Thread currentThread = Thread.currentThread();    //获取当前Thread的Values    Values values = values(currentThread);    if (values == null) {       values = initializeValues(currentThread);    }    //将T value存入Values中    values.put(this, value);//put()方法...}//获取当前Thread.Values,是Thread的内部类,封装数据用Values values(Thread current) {    return current.localValues;}//Returns the value of this variable for the current thread.//get()方法,从当前Thread中获取存储的值public T get() {   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 initializeValues(Thread current) {    return current.localValues = new Values();}
0 0