三分钟搞懂InheritableThreadLocal以及实战父子线程间的共享数据

实战

直接上测试类和结果:
在这里插入图片描述
可以看到当前类可以访问到ThreadLocal和InheritableThreadLocal的数据
新建的子线程可以访问InheritableThreadLocal的数据,而不能访问ThreadLocal的数据

源码:

/**
 * @author: 李自强
 * @description: lzqtest
 * @date: 2021/8/23 5:02 下午
 */
public class lzqtest {
    private InheritableThreadLocal<Integer> integerInheritableThreadLocal = new InheritableThreadLocal<>();
    private ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    @Test
    public void test() throws InterruptedException, ExecutionException {
        integerInheritableThreadLocal.set(999);
        threadLocal.set(666);
        System.out.println("father inherit:" + integerInheritableThreadLocal.get() +
                " threadLocal:" + threadLocal.get());
        new Thread(() -> System.out.println("son inherit:" + integerInheritableThreadLocal.get() +
                " threadLocal:" + threadLocal.get())).start();
    }
}

InheritableThreadLocal类结构:

继承了ThreadLocal,get、set方法用的都是父类的方法,只是重写了getMap和createMap:
在这里插入图片描述
源码:

ThreadLocalMap getMap(Thread t) {
   return t.inheritableThreadLocals;
}
 
void createMap(Thread t, T firstValue) {
    t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}

inheritableThreadLocals也是ThreadLocal.ThreadLocalMap对象

我们看一下Thread的构造方法:

public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

init方法:

private void init(ThreadGroup g, Runnable target, String name,
                  long stackSize, AccessControlContext acc,
                  boolean inheritThreadLocals) {
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }
 
    this.name = name;
 
    Thread parent = currentThread();
    SecurityManager security = System.getSecurityManager();
    if (g == null) {
        /* Determine if it's an applet or not */
 
        /* If there is a security manager, ask the security manager
           what to do. */
        if (security != null) {
            g = security.getThreadGroup();
        }
 
        /* If the security doesn't have a strong opinion of the matter
           use the parent thread group. */
        if (g == null) {
            g = parent.getThreadGroup();
        }
    }
 
    /* checkAccess regardless of whether or not threadgroup is
       explicitly passed in. */
    g.checkAccess();
 
    /*
     * Do we have the required permissions?
     */
    if (security != null) {
        if (isCCLOverridden(getClass())) {
            security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
        }
    }
 
    g.addUnstarted();
 
    this.group = g;
    this.daemon = parent.isDaemon();
    this.priority = parent.getPriority();
    if (security == null || isCCLOverridden(parent.getClass()))
        this.contextClassLoader = parent.getContextClassLoader();
    else
        this.contextClassLoader = parent.contextClassLoader;
    this.inheritedAccessControlContext =
            acc != null ? acc : AccessController.getContext();
    this.target = target;
    setPriority(priority);
    if (inheritThreadLocals && parent.inheritableThreadLocals != null)
        this.inheritableThreadLocals =
            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
    /* Stash the specified stack size in case the VM cares */
    this.stackSize = stackSize;
 
    /* Set thread ID */
    tid = nextThreadID();
}

关键代码:

// parent就是父线程,也就是执行new Thread()的线程
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
    this.inheritableThreadLocals =
        ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

这里会把父线程的inheritableThreadLocals赋值给子线程,从而实现了父子线程变量传递

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值