一、ThreadLocal 在父子线程传递的问题

public class InheritableThreadLocalDemo {

//    全局变量
// static ThreadLocal<String> threadLocal = new ThreadLocal<>();
static ThreadLocal<String> threadLocal = new InheritableThreadLocal<>(); public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
InheritableThreadLocalDemo.threadLocal.set("superWorld");
new Service().call();
}
}).start();
}
} class Service {
public void call() {
System.out.println("Service:" + Thread.currentThread().getName() + " : " + InheritableThreadLocalDemo.threadLocal.get());
//new Dao().call();
new Thread(new Runnable() {
@Override
public void run() {
new Dao().call();
}
}).start();
}
} class Dao {
public void call() {
System.out.println("Dao:" + Thread.currentThread().getName() + " : " + InheritableThreadLocalDemo.threadLocal.get());
} }

二、InheritableThreadLocal 和 ThreadLocal 的区别

1. InheritableThreadLocal 实现

public class InheritableThreadLocal<T> extends ThreadLocal<T> {
/**
* Computes the child's initial value for this inheritable thread-local
* variable as a function of the parent's value at the time the child
* thread is created. This method is called from within the parent
* thread before the child is started.
* <p>
* This method merely returns its input argument, and should be overridden
* if a different behavior is desired.
*
* @param parentValue the parent thread's value
* @return the child thread's initial value
*/
protected T childValue(T parentValue) {
return parentValue;
} /**
* Get the map associated with a ThreadLocal.
*
* @param t the current thread
*/
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
} /**
* Create the map associated with a ThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the table.
*/
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}

2. ThreadLocal 的getMap、createMap实现

    /**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
} /**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}

通过上面的代码我们可以看到InheritableThreadLocal 重写了childValue, getMap,createMap三个方法,

当我们往里面set值的时候,值保存到了inheritableThreadLocals里面,而不是之前的threadLocals。

三、问题:为什么当创建子线程时,可以获取到上个线程里的threadLocal中的值呢?

原因就是在新创建线程的时候,会把之前线程的inheritableThreadLocals赋值给新线程的inheritableThreadLocals,通过这种方式实现了数据的传递。

代码关键点:

1. Thread#init

if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

2. ThreadLocal.createInheritedMap

       static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
  return new ThreadLocalMap(parentMap);
  } private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len]; for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}

ThreadLocal (二):什么时候使用 InheritableThreadLocal的更多相关文章

  1. 理解ThreadLocal(二)

    首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的.各 ...

  2. 彻底理解ThreadLocal二

    首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的.各 ...

  3. 深入理解ThreadLocal(二)

    3 InheritableThreadLocal的使用 通过上面的分析知道通过ThreadLocal保存的值是线程隔离的.其实在Thread对象中,还有一个ThreadLocal.ThreadLoca ...

  4. 【并发编程】ThreadLocal的兄弟InheritableThreadLocal

    本博客系列是学习并发编程过程中的记录总结.由于文章比较多,写的时间也比较散,所以我整理了个目录贴(传送门),方便查阅. 并发编程系列博客传送门 引子 public class InheritableT ...

  5. java多线程系类:JUC线程池:03之线程池原理(二)(转)

    概要 在前面一章"Java多线程系列--"JUC线程池"02之 线程池原理(一)"中介绍了线程池的数据结构,本章会通过分析线程池的源码,对线程池进行说明.内容包 ...

  6. Java多线程系列--“JUC线程池”03之 线程池原理(二)

    概要 在前面一章"Java多线程系列--“JUC线程池”02之 线程池原理(一)"中介绍了线程池的数据结构,本章会通过分析线程池的源码,对线程池进行说明.内容包括:线程池示例参考代 ...

  7. 【Java】深入理解ThreadLocal

    一.前言 要理解ThreadLocal,首先必须理解线程安全.线程可以看做是一个具有一定独立功能的处理过程,它是比进程更细度的单位.当程序以单线程运行的时候,我们不需要考虑线程安全.然而当一个进程中包 ...

  8. ThreadLocal源码分析-黄金分割数的使用

    前提 最近接触到的一个项目要兼容新老系统,最终采用了ThreadLocal(实际上用的是InheritableThreadLocal)用于在子线程获取父线程中共享的变量.问题是解决了,但是后来发现对T ...

  9. java中threadlocal的理解

    [TOC] #java中threadlocal的理解##一.threadlocal的生命周期和ThreadLocalMap的生命周期可以吧TreadLocal看做是一个map来使用,只不过这个map是 ...

随机推荐

  1. EditPlus设置html和js文件的注释快捷键

    EditPlus默认是可以通过快捷键注释html的,格式是 <!-- </label> <label>类型</label> <label> --& ...

  2. Tomcat控制台输出

    在Tomcat中,默认将终端输出信息输出到: $CATALINA_HOME/logs/catalina.out  其中$CATALINA_HOME是tomcat的安装目录. tomcat启动后,该文件 ...

  3. iOS10 获取系统通讯录新方法

    #import <ContactsUI/ContactsUI.h> 遵循代理 CNContactPickerDelegate 调用通讯录 如果在iOS10的机器上调用以前的ABPeople ...

  4. 关于UITableView界面刷新

    在TableView中的数据发生改变的时候,往往会发现UITableView中的数据没有更新,通常需要滚动后才会更新. 这个是因为他的重绘机制的问题. 一般情况下可以用下面这个方法解决: 在viewW ...

  5. 设计模式中类的关系之实现(Realization)

    实现关系是用来描述接口和实现接口的类或者构建结构之间的关系,接口是操作的集合,而这些操作就用于规定类或者构建结构的一种服务. 在接口和类之间的实现关系中,类实现了接口,类中的操作实现了接口中所声明的操 ...

  6. Android开发学习秘籍笔记(十九)

    吼.花了2天最后做出了一个类似于蓝牙串口助手功能的小程序,事实上也是实习公司的要求---有一个蓝牙无线扫描枪,要求终端能够通过蓝牙连接到该设备,而且蓝牙无线扫描枪扫描二维码或者条形码的时候能够将二维码 ...

  7. 【HDU 5305】Friends 多校第二场(双向DFS)

    依据题意的话最多32条边,直接暴力的话 2 ^ 32肯定超时了.我们能够分两次搜索时间复杂度降低为 2 * 2  ^ 16 唯一须要注意的就是对眼下状态的哈希处理. 我採用的是 十进制表示法 跑的还是 ...

  8. spark通过合理设置spark.default.parallelism参数提高执行效率

    spark中有partition的概念(和slice是同一个概念,在spark1.2中官网已经做出了说明),一般每个partition对应一个task.在我的测试过程中,如果没有设置spark.def ...

  9. UML Rose2003完美破解攻略

    Rational Rose 2003 软件project画图软件 ,当然还不止画图,对于那些不想用英文版Rational Rose2003的同志们.这个Rational Rose2003 版本号已经汉 ...

  10. (转载)Unity中解析ini配置文件----INIParser

    大家好,我是孙广东.   转载请注明出处:http://blog.csdn.net/u010019717 更全的内容请看我的游戏蛮牛地址:http://www.unitymanual.com/spac ...