ThreadLocal和InheritableThreadLocal解析
ThreadLocal和InheritableThreadLocal解析
追忆100 发表于3个月前
ThreadLocal和InheritableThreadLocal解析
  • 发表于 3个月前
  • 阅读 0
  • 收藏 0
  • 点赞 0
  • 评论 0

InheritableThreadLocal 扩展了 ThreadLocal,为子线程提供从父线程那里继承的值,在创建子线程时,子线程会接收所有可继承的线程局部变量的初始值,以获得父线程所具有的值。

看代码:

package cn.com.mayue.jdk;
import org.junit.Test;

import static java.lang.System.out;

/**
 * Created by mayue on 2017/1/10.
 * log4j的MDC 实现中使用了 InheritableThreadLocalTest
 * 测试 InheritableThreadLocal 的线程的继承
 */
public class InheritableThreadLocalTest {
    /**
     * 测试 ThreadLocal
     */
    @Test
    public void testThreadLocal() {
        final ThreadLocal<String> local = new ThreadLocal<String>();
        exec(local);
    }

    /**
     * 测试 InheritableThreadLocal
     */
    @Test
    public void testInheritableThreadLocal() {
        final ThreadLocal<String> local = new InheritableThreadLocal<String>();
        exec(local);
    }

    private void exec(final ThreadLocal<String> local) {
        local.set("parent thread");
        out.println(Thread.currentThread() + "," + local.get());
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                out.println(Thread.currentThread() + "," + local.get());
                local.set("child thread");
                out.println(Thread.currentThread() + "," + local.get());
            }
        });

        t.start();
        try {
            //把创建的线程 合并到当前的线程中  方便看打印信息  打印信息和代码顺序一致
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        out.println(Thread.currentThread() + "," + local.get());
    }
}

方法testThreadLocal执行结果:

Thread[main,5,main],parent thread
Thread[Thread-0,5,main],null
Thread[Thread-0,5,main],child thread
Thread[main,5,main],parent thread

 

方法testInheritableThreadLocal执行结果:

Thread[main,5,main],parent thread
Thread[Thread-0,5,main],parent thread
Thread[Thread-0,5,main],child thread
Thread[main,5,main],parent thread

 

从执行结果中可以看出,InheritableThreadLocal可以获取父级线程的内容,而ThreadLocal不可以

共有 人打赏支持
粉丝 0
博文 9
码字总数 3297
×
追忆100
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: