InheritableThreadLocal:子线程继承父线程的本地变量

Posted 快乐崇拜234

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了InheritableThreadLocal:子线程继承父线程的本地变量相关的知识,希望对你有一定的参考价值。

欢迎关注本人公众号

线程本地变量相关的博客目录

概述

ThreadLocal可以保存一些变量仅供当前线程使用,其他线程不可见。
实际工作中可能会由于任务复杂,父线程创建几个子线程并发致性任务,那么父线程的本地变量如何传递到子线程呢? 答案是使用InheritableThreadLocal。

代码实例

public static ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<>();

    public static void main(String[] args) throws Exception 
        threadLocal.set(12345);
        Thread thread = new MyThread();
        thread.start();
        System.out.println("main = " + threadLocal.get());
    

    static class MyThread extends Thread 
        @Override
        public void run() 
            System.out.println("MyThread = " + threadLocal.get());
        
    

运行结果:

main = 12345
MyThread = 12345

子线程中获取到了父线程的变量值。

如果将InheritableThreadLocal换为ThreadLocal,则子线程打印结果为MyThread = null,读者自行验证。

源码分析

public class InheritableThreadLocal<T> extends ThreadLocal<T> 
/**
* 重写了childValue方法
* 父线程创建子线程时,向子线程复制InheritableThreadLocal变量时使用
*/
    protected T childValue(T parentValue) 
        return parentValue;
    
    //注意这里使用的是Thread对象里的inheritableThreadLocals变量,而不是threadLocals
    ThreadLocalMap getMap(Thread t) 
       return t.inheritableThreadLocals;
    
    //将父线程的threadLocal变量拷贝到子线程
    void createMap(Thread t, T firstValue) 
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    

当我们在new Thread()时,会有从父线程拷贝线程本地变量到子线程的代码:

public Thread() 
        this(null, null, "Thread-" + nextThreadNum(), 0);
    
 public Thread(ThreadGroup group, Runnable target, String name,
                  long stackSize) 
        this(group, target, name, stackSize, null, true);
    
private Thread(ThreadGroup g, Runnable target, String name,
                   long stackSize, AccessControlContext acc,
                   boolean inheritThreadLocals) 
        //省略...
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        //省略
        

默认情况下,inheritThreadLocals值为true,parent.inheritableThreadLocals也不为空,所以会执行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 (Entry e : parentTable) 
            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++;
                
            
        
    

这段代码比较简单,就是在创建子线程时逐个读取父线程的本地变量,赋值给子线程本地变量。

以上是关于InheritableThreadLocal:子线程继承父线程的本地变量的主要内容,如果未能解决你的问题,请参考以下文章

InheritableThreadLocal详解

多线程-InheritableThreadLocal

InheritableThreadLocal原理解析

InheritableThreadLocal线程复用

InheritableThreadLocal:子线程继承父线程的本地变量

将 InheritableThreadLocal 与 ThreadPoolExecutor - 或 - 不重用线程的 ThreadPoolExecutor 一起使用