ThreadLocal 在我们做线程级的数据隔离时非常好用,但是有时候多级线程无法获取,比如SpringBoot中的 异步,这时会想如何让子线程获取到父线程的ThreadLocal,其实在线程中除了ThreadLocal外还有 InheritableThreadLocal,顾名思义,可继承的线程变量表,可以让子线程获取到父线程中ThreadLocal的值。


import static java.lang.String.format;

public class Test {

    public static final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
    public static final ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        inheritableThreadLocal.set("My Inheritable");
        threadLocal.set("threadLocal");
        System.out.println(format("当前线程Inheritable值:%s", inheritableThreadLocal.get()));
        System.out.println(format("当前线程值:%s", threadLocal.get()));

        new Thread(() -> {
            System.out.println(format("子线程Inheritable值:%s", inheritableThreadLocal.get()));
            System.out.println(format("子线程值:%s", threadLocal.get()));
            new Thread(() -> {
                System.out.println(format("孙子线程Inheritable值:%s", inheritableThreadLocal.get()));
                System.out.println(format("孙子线程值:%s", threadLocal.get()));
                new Thread(() -> {
                    System.out.println(format("曾子线程Inheritable值:%s", inheritableThreadLocal.get()));
                    System.out.println(format("曾子线程值:%s", threadLocal.get()));
                }).start();

            }).start();

        }).start();
    }

}




点赞(0) 打赏

Comment list 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部