一、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. 转:VLC搭建RTSP直播流,图文介绍

    将一个视频转成rtsp流,通过vlc播放器,搭建一个rtsp服务器,让rtsp客户端去访问这个视频的rtsp流 1 需要有vlc播放器,我的版本如下 2  媒体 -->  流 3  添加视频文件 ...

  2. 【精】iOS GCD 具体解释

    一.介绍 1.什么是GCD? Grand Central Dispatch.是苹果公司开发的一套多核编程的底层API. GCD首次公布在Mac OS X 10.6,iOS4及以上也可用.GCD存在于l ...

  3. VS2015 解决方案 或者项目 卡 正在加载 的解决办法

    导致项目无法打开以及VS无法关闭. 解决方法: 1.关闭VS: 2.去C:\Users\<your users name>\AppData\Local\Microsoft\VisualSt ...

  4. SDRAM驱动篇之简易SDRAM控制器的verilog代码实现

    在Kevin写的上一篇博文<SDRAM理论篇之基础知识及操作时序>中,已经把SDRAM工作的基本原理和SDRAM初始化.读.写及自动刷新操作的时序讲清楚了,在这一片博文中,Kevin来根据 ...

  5. Matlab中使用Java api画图图形并保存为jpeg格式

    直接上代码: close all; import java.io.*; import java.awt.*; import java.awt.image.BufferedImage; import j ...

  6. c++ telescoping constructor is NOT supported until c++11

    Telescoping constructor: see Effective Java 2nd Edition Item 2 If you want to use telescoping constr ...

  7. Python 2.7 中使用 Print 方法

    print ("test",file=name)类似的方法在python 2中需要先引入 __future__才可使用 import __futhure__ import prin ...

  8. hdu1018 Big Number 斯特林公式 求N!的位数。

    Big Number Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total ...

  9. python 反射机制 ( 广泛应用于URL参数)

    web实例 考虑有这么一个场景,根据用户输入的url的不同,调用不同的函数,实现不同的操作,也就是一个url路由器的功能,这在web框架里是核心部件之一.下面有一个精简版的示例: 首先,有一个comm ...

  10. ThinkPHP带表情无限级评论回复

    今天就tp中(含表情)无限级评论回复做一个个人总结. 1.准备TP基本框架 2.数据库,数据表的建立 A.先说说数据库(表)的建立. a-1,数据库:blog a-2,数据表:bolg_comment ...