一、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. olede读excel

    注意点:需要比较excel文件中是否有重复列时,需要设置HDR=No,IMEX=1,即把第一列当做数据读取,不然读到的datatable列名会被自动加数字后缀. /// < summary> ...

  2. Ioc(控制反转)、DI(依赖注入)

    一篇非常好的有关控制反转和依赖注入非常不错的文章,简单易通,与大家共同学习,这里只引用了一篇文章,还有很多相关的文章可以通过文章引用地址来看,相信大家看完理解的就比较深刻了 文章摘自:http://j ...

  3. Silverlight实例教程 - Validation服务器端异步数据验证(转载)

    摘要:本 篇实例,我们仍旧使用SilverlightValidationDemo项目,为了不和过去的验证方法冲突,这里我们创建一个新的数据成员类 Staff,该类实现INotifyDataErrorI ...

  4. Atitit.跨语言数据库db  api兼容性 jdbc odbc ado oledb 增强方案

    Atitit.跨语言数据库db  api兼容性 jdbc odbc ado oledb 增强方案 1. 跨语言db api兼容性..1 2. 目前访问数据库的接口很多.比较常用的jdbc odbc 以 ...

  5. spring boot 多层级mapper

    mapper目录结构:   mapper ----dev -------produce   在 application.properties 文件中配置 mybatis.mapper-location ...

  6. python简单处理xml文件

    Python若是想从xml里读点信息,用BeautifulSoup可能会容易一点,但是如果要修改xml,BeatifulSoup就搞不定了,其实直接用lxml就好. from lxml import ...

  7. linux内核常用函数或宏

    1. simple_strtoul 用于将字符串转换为无符号长整数,第3个参数10意味着转换方式是10进制. ival = simple_strtoul(buffer, NULL, 10); 2. 大 ...

  8. X264参考手册

    艺搜简介 基本语法: x264 [options]-o outfile infile 注意与ffmpeg的输入输出文件位置恰好相反: ffmpeg[options][[infile options]- ...

  9. svn密码 在服务端 到底是明文保存,还是密文保存

    svn密码 在服务端 到底是明文保存,还是密文保存 之前在ubuntu上搭建svn服务端,记得密码就是明文保存的, 但最近项目,我们老大说,他搭建的是加密后的,我就比较纳闷了, 经过偷偷的瞄一下,不就 ...

  10. hdu5334(2015多校4)--Virtual Participation(构造)

    题目链接:pid=5334">点击打开链接 题目大意:给出一个数字k,要求做出一个长度小于等于10^5的序列.该序列中不同样的连续子序列有k个. 构造啊,.,,,,一点辙都没有 使用连 ...