
在不同线程中保存同一种类型的不同对象
如上图:在main线程中初始化,在main线程获取就是“张三”。在thread1设置“李四”,在thread1中获取就是“李四”,不会更改main线程中的“张三”。
原理:
ThreadLocal中

步骤1:获取当前线程 Thread t,
步骤2:根据当前线程 t 获取ThreadLocalMap

获取到的threadLocals在Thread类中被定义,是Thread类中的属性

在获取的时候获取当前线程 t,获取线程中的map,获取map中存储的value值。
疑惑:通过set方法与get方法看上去很像hashmap中的key,value形式以 thread为key,存储value。
解答:在set与get方法中都有ThreadLocalMap map = getMap(t),把这句换成
ThreadLocalMap map = t.threadLocals。就明白获取的是thread中的ThreadLocalMap。在不同线程中当然有不同的ThreadLocalMap对象,获取的值也是不同的。
ThreadLocalMap类中的Entry类是用来真正保存数据的存储的数据格式为:key为ThreadLocal<?> ,value为object。为什么?这是用来存储多个ThreadLocal。一个ThreadLocal只能存储一种如String,想存储Integer就再new一个。
总结:用我们熟悉的面向对象来写
class Thread{
private Map map = new Map();
set(){
map.put();
}
get(){
return map.get();
}
}
Thread thread=new Thread();
thread.set()
thread.get()//获取的数据就是上面set的数据
网友评论