理解ThreadLocal
2016-02-15 15:32
344 查看
参考
正确理解TheadLocal
%E8%A7%A3%E5%AF%86ThreadLocal/]解密ThreadLocal
JDK文档
ThreadLocal
在同步机制中,通过对象的锁机制保证同一时间只有一个线程访问变量。这时该变量是多个线程共享的。
使用同步机制要求程序慎密地分析什么时候对变量进行读写,什么时候需要锁定某个对象,什么时候释放对象锁等繁杂的问题。
经典案例:多生产者和多消费者。
ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。(ThreadLocalVariables可能更好理解点)
个人理解:每个线程中各自用独立的对象。可以很方便的获取在本线程中存储的对象,拍案惊奇!!!应该要有一个ThreadLocalMananger,保持ThreadLocal为单例,在Handler机制里面Looper中为static final,被所有线程中Looper共享。
当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候,可以考虑采用ThreadLocal。
Thread中持有TreadLocal.Values,
每一个线程就有一个Values,所以每一个线程都有Object[]数组 table。通过数组角标来获取该线程局部变量。
正确理解TheadLocal
%E8%A7%A3%E5%AF%86ThreadLocal/]解密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(); }
相关文章推荐
- spring实现定时任务的两种方式之Spring 3整合Quartz 2实现定时任务
- 如何配置开源中国Maven库以加快依赖包下载速度
- android app学习笔记
- C# 使用属性实现位状态结构体
- html之线包字
- python编程常用总结
- 类簇在iOS开发中的应用
- Linux系统移植002: 编译Uboot 2014.04 基于AT91SAM9X35EK
- php调用com组件加载dos命令解压缩的方法
- [New learn] 手势
- 文件操作(汇总)
- HDOJ 5627 Clarke and MST (位运算最大生成树kruskul)
- C语言int的取值范围
- 20160215
- Oracle学习之数据库管理(二)索引&约束&表分区
- 使用child_process 执行命令
- js中的||与&&用法
- linux下导入、导出mysql数据库命令
- Linux下面配置Apache2 + tomcat7.0 + ssl 集群安装与配置
- Maven笔记